Skip to content

Commit

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

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

Expand Down

0 comments on commit 82438ad

Please sign in to comment.