From 436d9c807af33defecd36a4cc6a6b72c78d601a8 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Mon, 12 Aug 2024 08:04:21 +0200 Subject: [PATCH] buffer: optimize createFromString PR-URL: https://github.com/nodejs/node/pull/54324 --- lib/buffer.js | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index 4e6031afdb3919..d5b3f7ae5c7799 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -442,27 +442,37 @@ function allocate(size) { } function fromStringFast(string, ops) { - const length = ops.byteLength(string); + const stringLength = string.length; - if (length >= (Buffer.poolSize >>> 1)) + if (stringLength > Buffer.poolSize) + return createFromString(string, ops.encodingVal); + + let length = stringLength * 4; // max utf8 byte length + + if (length > Buffer.poolSize) + length = ops.byteLength(string); + + if (length * 2 > Buffer.poolSize) return createFromString(string, ops.encodingVal); if (length > (poolSize - poolOffset)) createPool(); + let b = new FastBuffer(allocPool, poolOffset, length); const actual = ops.write(b, string, 0, length); if (actual !== length) { - // byteLength() may overestimate. That's a rare case, though. b = new FastBuffer(allocPool, poolOffset, actual); } + poolOffset += actual; alignPool(); + return b; } function fromString(string, encoding) { let ops; - if (typeof encoding !== 'string' || encoding.length === 0) { + if (typeof encoding !== 'string' || encoding === 'utf8' || encoding.length === 0) { if (string.length === 0) return new FastBuffer(); ops = encodingOps.utf8;