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 e470948
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],

Check failure on line 9 in benchmark/buffers/buffer-write-string.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

A space is required after ','

Check failure on line 9 in benchmark/buffers/buffer-write-string.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

A space is required after ','

Check failure on line 9 in benchmark/buffers/buffer-write-string.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

A space is required after ','
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(0);
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 e470948

Please sign in to comment.