Skip to content

Commit

Permalink
buffer: optimize writing short strings
Browse files Browse the repository at this point in the history
PR-URL: #54310
  • Loading branch information
ronag committed Aug 10, 2024
1 parent 5d6c76a commit a9fd9ac
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
2 changes: 1 addition & 1 deletion benchmark/buffers/buffer-write-string.js
Original file line number Diff line number Diff line change
Expand Up @@ -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],
});

Expand Down
29 changes: 26 additions & 3 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);

Expand Down

0 comments on commit a9fd9ac

Please sign in to comment.