Skip to content

Commit b6c9912

Browse files
committed
buffer: optimize byteLength for common encodings
PR-URL: #54342
1 parent 298ff4f commit b6c9912

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

lib/buffer.js

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -771,13 +771,22 @@ function byteLength(string, encoding) {
771771
if (len === 0)
772772
return 0;
773773

774-
if (encoding) {
775-
const ops = getEncodingOps(encoding);
776-
if (ops) {
777-
return ops.byteLength(string);
778-
}
774+
if (!encoding || encoding === 'utf8') {
775+
return byteLengthUtf8(string);
776+
}
777+
778+
if (encoding === 'ascii') {
779+
return len;
779780
}
780-
return byteLengthUtf8(string);
781+
782+
const ops = getEncodingOps(encoding);
783+
if (ops === undefined) {
784+
// TODO (ronag): Makes more sense to throw here.
785+
// throw new ERR_UNKNOWN_ENCODING(encoding);
786+
return byteLengthUtf8(string);
787+
}
788+
789+
return ops.byteLength(string);
781790
}
782791

783792
Buffer.byteLength = byteLength;

0 commit comments

Comments
 (0)