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 9b240c1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 11 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
18 changes: 14 additions & 4 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -442,27 +442,37 @@ function allocate(size) {
}

function fromStringFast(string, ops) {
const length = ops.byteLength(string);
const stringLength = string.length

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

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

if (length > Buffer.poolSize)
length = ops.byteLength(string);

if (length * 2 > Buffer.poolSize)
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;
}

function fromString(string, encoding) {
let ops;
if (typeof encoding !== 'string' || encoding.length === 0) {
if (typeof encoding !== 'string' || encoding === 'utf8' || encoding.length === 0) {
if (string.length === 0)
return new FastBuffer();
ops = encodingOps.utf8;
Expand Down

0 comments on commit 9b240c1

Please sign in to comment.