From 82438adf4ea983a6739fc9fe26a31615200b014e 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 --- benchmark/buffers/buffer-write-string.js | 6 +++--- lib/buffer.js | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/benchmark/buffers/buffer-write-string.js b/benchmark/buffers/buffer-write-string.js index 9d9e8a93391737..237c03187b3ef3 100644 --- a/benchmark/buffers/buffer-write-string.js +++ b/benchmark/buffers/buffer-write-string.js @@ -3,10 +3,10 @@ const common = require('../common.js'); const bench = common.createBenchmark(main, { encoding: [ - '', 'utf8', 'ascii', 'hex', 'utf16le', 'latin1', + 'utf8', ], - args: [ '', 'offset', 'offset+length' ], - len: [2048], + args: [ '' ], + len: [1,8,16,32, 64], n: [1e6], }); diff --git a/lib/buffer.js b/lib/buffer.js index 4e6031afdb3919..94dced80c57b8b 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -1108,6 +1108,24 @@ Buffer.prototype.write = function write(string, offset, length, encoding) { } } + const len = string.length; + if (len <= 32 && len <= length) { + let n = 0; + while (true) { + const code = string.charCodeAt(n); + if (code >= 128) { + break; + } + + this[offset + n] = code; + n++; + + if (n === len) { + return len; + } + } + } + if (!encoding) return this.utf8Write(string, offset, length);