Skip to content

Commit

Permalink
lib: avoid .toLowerCase() call in Buffer#write()
Browse files Browse the repository at this point in the history
Avoid a costly String#toLowerCase() call in Buffer#write() in the
common case, i.e., that the string is already lowercase.  Reduces
the running time of the following benchmark by about 40%:

    for (var b = Buffer(1), i = 0; i < 25e6; ++i) b.write('x', 'ucs2');

PR-URL: #1048
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
  • Loading branch information
bnoordhuis committed Mar 5, 2015
1 parent bbf54a5 commit 4ddd640
Showing 1 changed file with 29 additions and 31 deletions.
60 changes: 29 additions & 31 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -480,47 +480,45 @@ Buffer.prototype.write = function(string, offset, length, encoding) {
if (length === undefined || length > remaining)
length = remaining;

encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';

if (string.length > 0 && (length < 0 || offset < 0))
throw new RangeError('attempt to write outside buffer bounds');

var ret;
switch (encoding) {
case 'hex':
ret = this.hexWrite(string, offset, length);
break;
if (!encoding)
encoding = 'utf8';

case 'utf8':
case 'utf-8':
ret = this.utf8Write(string, offset, length);
break;
var loweredCase = false;
for (;;) {
switch (encoding) {
case 'hex':
return this.hexWrite(string, offset, length);

case 'ascii':
ret = this.asciiWrite(string, offset, length);
break;
case 'utf8':
case 'utf-8':
return this.utf8Write(string, offset, length);

case 'binary':
ret = this.binaryWrite(string, offset, length);
break;
case 'ascii':
return this.asciiWrite(string, offset, length);

case 'base64':
// Warning: maxLength not taken into account in base64Write
ret = this.base64Write(string, offset, length);
break;
case 'binary':
return this.binaryWrite(string, offset, length);

case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = this.ucs2Write(string, offset, length);
break;
case 'base64':
// Warning: maxLength not taken into account in base64Write
return this.base64Write(string, offset, length);

default:
throw new TypeError('Unknown encoding: ' + encoding);
}
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return this.ucs2Write(string, offset, length);

return ret;
default:
if (loweredCase)
throw new TypeError('Unknown encoding: ' + encoding);
encoding = ('' + encoding).toLowerCase();
loweredCase = true;
}
}
};


Expand Down

0 comments on commit 4ddd640

Please sign in to comment.