Skip to content

Commit 4ddd640

Browse files
committed
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: #1048 Reviewed-By: Trevor Norris <[email protected]>
1 parent bbf54a5 commit 4ddd640

File tree

1 file changed

+29
-31
lines changed

1 file changed

+29
-31
lines changed

lib/buffer.js

+29-31
Original file line numberDiff line numberDiff line change
@@ -480,47 +480,45 @@ Buffer.prototype.write = function(string, offset, length, encoding) {
480480
if (length === undefined || length > remaining)
481481
length = remaining;
482482

483-
encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
484-
485483
if (string.length > 0 && (length < 0 || offset < 0))
486484
throw new RangeError('attempt to write outside buffer bounds');
487485

488-
var ret;
489-
switch (encoding) {
490-
case 'hex':
491-
ret = this.hexWrite(string, offset, length);
492-
break;
486+
if (!encoding)
487+
encoding = 'utf8';
493488

494-
case 'utf8':
495-
case 'utf-8':
496-
ret = this.utf8Write(string, offset, length);
497-
break;
489+
var loweredCase = false;
490+
for (;;) {
491+
switch (encoding) {
492+
case 'hex':
493+
return this.hexWrite(string, offset, length);
498494

499-
case 'ascii':
500-
ret = this.asciiWrite(string, offset, length);
501-
break;
495+
case 'utf8':
496+
case 'utf-8':
497+
return this.utf8Write(string, offset, length);
502498

503-
case 'binary':
504-
ret = this.binaryWrite(string, offset, length);
505-
break;
499+
case 'ascii':
500+
return this.asciiWrite(string, offset, length);
506501

507-
case 'base64':
508-
// Warning: maxLength not taken into account in base64Write
509-
ret = this.base64Write(string, offset, length);
510-
break;
502+
case 'binary':
503+
return this.binaryWrite(string, offset, length);
511504

512-
case 'ucs2':
513-
case 'ucs-2':
514-
case 'utf16le':
515-
case 'utf-16le':
516-
ret = this.ucs2Write(string, offset, length);
517-
break;
505+
case 'base64':
506+
// Warning: maxLength not taken into account in base64Write
507+
return this.base64Write(string, offset, length);
518508

519-
default:
520-
throw new TypeError('Unknown encoding: ' + encoding);
521-
}
509+
case 'ucs2':
510+
case 'ucs-2':
511+
case 'utf16le':
512+
case 'utf-16le':
513+
return this.ucs2Write(string, offset, length);
522514

523-
return ret;
515+
default:
516+
if (loweredCase)
517+
throw new TypeError('Unknown encoding: ' + encoding);
518+
encoding = ('' + encoding).toLowerCase();
519+
loweredCase = true;
520+
}
521+
}
524522
};
525523

526524

0 commit comments

Comments
 (0)