From d04246a0d73a394c5b32268fde2c22237d0f7b8f Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Wed, 14 Aug 2024 21:46:48 +0200 Subject: [PATCH] buffer: optimize byteLength for common encodings PR-URL: https://github.com/nodejs/node/pull/54342 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Yagiz Nizipli Reviewed-By: Luigi Pinca --- lib/buffer.js | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index 074966dd55b59b..81c0c5e2830c5c 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -780,13 +780,22 @@ function byteLength(string, encoding) { if (len === 0) return 0; - if (encoding) { - const ops = getEncodingOps(encoding); - if (ops) { - return ops.byteLength(string); - } + if (!encoding || encoding === 'utf8') { + return byteLengthUtf8(string); + } + + if (encoding === 'ascii') { + return len; } - return byteLengthUtf8(string); + + 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;