Skip to content

Commit

Permalink
buffer: optimize createFromString
Browse files Browse the repository at this point in the history
PR-URL: nodejs#54324
  • Loading branch information
ronag committed Aug 12, 2024
1 parent 298ff4f commit 59263f4
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
14 changes: 7 additions & 7 deletions benchmark/buffers/buffer-from.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@ const common = require('../common.js');
const assert = require('assert');
const bench = common.createBenchmark(main, {
source: [
'array',
'arraybuffer',
'arraybuffer-middle',
'buffer',
// 'array',
// 'arraybuffer',
// 'arraybuffer-middle',
// 'buffer',
'string',
'string-utf8',
'string-base64',
'object',
'uint8array',
'uint16array',
// 'object',
// 'uint8array',
// 'uint16array',
],
len: [100, 2048],
n: [8e5],
Expand Down
17 changes: 14 additions & 3 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -442,21 +442,32 @@ function allocate(size) {
}

function fromStringFast(string, ops) {
const length = ops.byteLength(string);
const maxPoolLength = Buffer.poolSize >>> 1;
const stringLength = string.length

if (length >= (Buffer.poolSize >>> 1))
if (stringLength > maxPoolLength)
return createFromString(string, ops.encodingVal);

let length = stringLength * 4; // max utf8 byte length

if (length >= maxPoolLength)
length = ops.byteLength(string);

if (length >= maxPoolLength)
return createFromString(string, ops.encodingVal);

if (length > (poolSize - poolOffset))
createPool();

let b = new FastBuffer(allocPool, poolOffset, length);
const actual = ops.write(b, string, 0, length);
if (actual !== length) {
// byteLength() may overestimate. That's a rare case, though.
b = new FastBuffer(allocPool, poolOffset, actual);
}

poolOffset += actual;
alignPool();

return b;
}

Expand Down

0 comments on commit 59263f4

Please sign in to comment.