Browse Source

buffer: optimize common encoding cases

String#toLowerCase() is incredibly slow and was costing a 15-30%
performance hit for Buffers less than 1KB. Now instead it'll attempt to
find the correct encoding directly from the passed encoding, only then
afterwards it'll lowercase.

The optimization for not passing any encoding at all is still at the top
of the method.

At most this may add 10% performance hit for passing a mixed case
encoding.
v0.11.8-release
Trevor Norris 12 years ago
parent
commit
59dac01e4e
  1. 12
      lib/buffer.js

12
lib/buffer.js

@ -202,15 +202,17 @@ Buffer.prototype.parent = undefined;
// toString(encoding, start=0, end=buffer.length)
Buffer.prototype.toString = function(encoding, start, end) {
encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
var loweredCase = false;
start = ~~start;
end = util.isUndefined(end) ? this.length : ~~end;
start = start >>> 0;
end = util.isUndefined(end) ? this.length : end >>> 0;
if (!encoding) encoding = 'utf8';
if (start < 0) start = 0;
if (end > this.length) end = this.length;
if (end <= start) return '';
while (true) {
switch (encoding) {
case 'hex':
return this.hexSlice(start, end);
@ -235,7 +237,11 @@ Buffer.prototype.toString = function(encoding, start, end) {
return this.ucs2Slice(start, end);
default:
if (loweredCase)
throw new TypeError('Unknown encoding: ' + encoding);
encoding = (encoding + '').toLowerCase();
loweredCase = true;
}
}
};

Loading…
Cancel
Save