From 4ddd6406ce1c474e1a54a5aa9b56f7554902fd10 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Wed, 4 Mar 2015 01:09:33 +0100 Subject: [PATCH] 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 --- lib/buffer.js | 60 +++++++++++++++++++++++++-------------------------- 1 file changed, 29 insertions(+), 31 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index ba832de975..5427a5a5a6 100644 --- a/lib/buffer.js +++ b/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; + } + } };