From 28ca678f81e3579800d7201fbdad498d16cc0995 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 a68718848c1a49..05b57275f03dca 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -782,13 +782,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;