From a9fd9ac3b80da88398b89db4a9ebba9f76c4a587 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Sat, 10 Aug 2024 20:49:11 +0200 Subject: [PATCH] buffer: optimize writing short strings PR-URL: https://github.com/nodejs/node/pull/54310 --- benchmark/buffers/buffer-write-string.js | 2 +- lib/buffer.js | 29 +++++++++++++++++++++--- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/benchmark/buffers/buffer-write-string.js b/benchmark/buffers/buffer-write-string.js index 9d9e8a93391737..80f438f52a6b2b 100644 --- a/benchmark/buffers/buffer-write-string.js +++ b/benchmark/buffers/buffer-write-string.js @@ -6,7 +6,7 @@ const bench = common.createBenchmark(main, { '', 'utf8', 'ascii', 'hex', 'utf16le', 'latin1', ], args: [ '', 'offset', 'offset+length' ], - len: [2048], + len: [1, 8, 16, 2048], n: [1e6], }); diff --git a/lib/buffer.js b/lib/buffer.js index 4e6031afdb3919..f32a06c6827fe3 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -1082,10 +1082,10 @@ function _fill(buf, value, offset, end, encoding) { Buffer.prototype.write = function write(string, offset, length, encoding) { // Buffer#write(string); if (offset === undefined) { - return this.utf8Write(string, 0, this.length); - } + offset = 0; + length = this.length; // Buffer#write(string, encoding) - if (length === undefined && typeof offset === 'string') { + } else if (length === undefined && typeof offset === 'string') { encoding = offset; length = this.length; offset = 0; @@ -1108,6 +1108,29 @@ Buffer.prototype.write = function write(string, offset, length, encoding) { } } + const len = string?.length; + if ( + len <= 16 && + len <= length && + (!encoding || encoding === 'ascii' || encoding === 'utf8') && + typeof string === 'string' + ) { + let n = 0; + while (true) { + const code = StringPrototypeCharCodeAt(string, n); + if (code >= 128) { + break; + } + + this[offset + n] = code; + n++; + + if (n === len) { + return len; + } + } + } + if (!encoding) return this.utf8Write(string, offset, length);