Skip to content

Commit d04246a

Browse files
ronagtargos
authored andcommittedOct 2, 2024
buffer: optimize byteLength for common encodings
PR-URL: #54342 Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
1 parent 8c8708c commit d04246a

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed
 

‎lib/buffer.js

+15-6
Original file line numberDiff line numberDiff line change
@@ -780,13 +780,22 @@ function byteLength(string, encoding) {
780780
if (len === 0)
781781
return 0;
782782

783-
if (encoding) {
784-
const ops = getEncodingOps(encoding);
785-
if (ops) {
786-
return ops.byteLength(string);
787-
}
783+
if (!encoding || encoding === 'utf8') {
784+
return byteLengthUtf8(string);
785+
}
786+
787+
if (encoding === 'ascii') {
788+
return len;
788789
}
789-
return byteLengthUtf8(string);
790+
791+
const ops = getEncodingOps(encoding);
792+
if (ops === undefined) {
793+
// TODO (ronag): Makes more sense to throw here.
794+
// throw new ERR_UNKNOWN_ENCODING(encoding);
795+
return byteLengthUtf8(string);
796+
}
797+
798+
return ops.byteLength(string);
790799
}
791800

792801
Buffer.byteLength = byteLength;

0 commit comments

Comments
 (0)
Please sign in to comment.