Skip to content

Commit 16ea356

Browse files
committed
buffer: improve Buffer.byteLength(string, encoding)
When string is empty, it will running into binding also. It make the performance is wasted.
1 parent 10e31ba commit 16ea356

File tree

1 file changed

+18
-14
lines changed

1 file changed

+18
-14
lines changed

lib/buffer.js

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -276,23 +276,27 @@ function byteLength(string, encoding) {
276276
if (typeof(string) !== 'string')
277277
string = String(string);
278278

279-
switch (encoding) {
280-
case 'ascii':
281-
case 'binary':
282-
case 'raw':
283-
return string.length;
279+
if (string.length > 0) {
280+
switch (encoding) {
281+
case 'ascii':
282+
case 'binary':
283+
case 'raw':
284+
return string.length;
284285

285-
case 'ucs2':
286-
case 'ucs-2':
287-
case 'utf16le':
288-
case 'utf-16le':
289-
return string.length * 2;
286+
case 'ucs2':
287+
case 'ucs-2':
288+
case 'utf16le':
289+
case 'utf-16le':
290+
return string.length * 2;
290291

291-
case 'hex':
292-
return string.length >>> 1;
293-
}
292+
case 'hex':
293+
return string.length >>> 1;
294+
}
294295

295-
return binding.byteLength(string, encoding);
296+
return binding.byteLength(string, encoding);
297+
} else {
298+
return 0;
299+
}
296300
}
297301

298302
Buffer.byteLength = byteLength;

0 commit comments

Comments
 (0)