From 16ea356ad0c3b4bbb5d3df8c4559550c5d2eda47 Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Thu, 16 Apr 2015 23:31:34 +0800 Subject: [PATCH] buffer: improve Buffer.byteLength(string, encoding) When string is empty, it will running into binding also. It make the performance is wasted. --- lib/buffer.js | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index f125806622d49d..86f66834f39f3f 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -276,23 +276,27 @@ function byteLength(string, encoding) { if (typeof(string) !== 'string') string = String(string); - switch (encoding) { - case 'ascii': - case 'binary': - case 'raw': - return string.length; + if (string.length > 0) { + switch (encoding) { + case 'ascii': + case 'binary': + case 'raw': + return string.length; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return string.length * 2; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return string.length * 2; - case 'hex': - return string.length >>> 1; - } + case 'hex': + return string.length >>> 1; + } - return binding.byteLength(string, encoding); + return binding.byteLength(string, encoding); + } else { + return 0; + } } Buffer.byteLength = byteLength;