Browse Source

lib: avoid .toLowerCase() call in Buffer#write()

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: https://github.com/iojs/io.js/pull/1048
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
v1.8.0-commit
Ben Noordhuis 10 years ago
parent
commit
4ddd6406ce
  1. 60
      lib/buffer.js

60
lib/buffer.js

@ -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;
}
}
};

Loading…
Cancel
Save