buffer: optimize byteLength for common encodings

PR-URL: https://github.com/nodejs/node/pull/54342
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
This commit is contained in:
Robert Nagy 2024-08-14 21:46:48 +02:00 committed by GitHub
parent 4e6befd60e
commit 38ad892ccf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -782,13 +782,22 @@ function byteLength(string, encoding) {
if (len === 0) if (len === 0)
return 0; return 0;
if (encoding) { if (!encoding || encoding === 'utf8') {
const ops = getEncodingOps(encoding); return byteLengthUtf8(string);
if (ops) {
return ops.byteLength(string);
}
} }
return byteLengthUtf8(string);
if (encoding === 'ascii') {
return len;
}
const ops = getEncodingOps(encoding);
if (ops === undefined) {
// TODO (ronag): Makes more sense to throw here.
// throw new ERR_UNKNOWN_ENCODING(encoding);
return byteLengthUtf8(string);
}
return ops.byteLength(string);
} }
Buffer.byteLength = byteLength; Buffer.byteLength = byteLength;