Skip to content

Commit 59263f4

Browse files
committed
buffer: optimize createFromString
PR-URL: #54324
1 parent 298ff4f commit 59263f4

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

benchmark/buffers/buffer-from.js

+7-7
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,16 @@ const common = require('../common.js');
44
const assert = require('assert');
55
const bench = common.createBenchmark(main, {
66
source: [
7-
'array',
8-
'arraybuffer',
9-
'arraybuffer-middle',
10-
'buffer',
7+
// 'array',
8+
// 'arraybuffer',
9+
// 'arraybuffer-middle',
10+
// 'buffer',
1111
'string',
1212
'string-utf8',
1313
'string-base64',
14-
'object',
15-
'uint8array',
16-
'uint16array',
14+
// 'object',
15+
// 'uint8array',
16+
// 'uint16array',
1717
],
1818
len: [100, 2048],
1919
n: [8e5],

lib/buffer.js

+14-3
Original file line numberDiff line numberDiff line change
@@ -442,21 +442,32 @@ function allocate(size) {
442442
}
443443

444444
function fromStringFast(string, ops) {
445-
const length = ops.byteLength(string);
445+
const maxPoolLength = Buffer.poolSize >>> 1;
446+
const stringLength = string.length
446447

447-
if (length >= (Buffer.poolSize >>> 1))
448+
if (stringLength > maxPoolLength)
449+
return createFromString(string, ops.encodingVal);
450+
451+
let length = stringLength * 4; // max utf8 byte length
452+
453+
if (length >= maxPoolLength)
454+
length = ops.byteLength(string);
455+
456+
if (length >= maxPoolLength)
448457
return createFromString(string, ops.encodingVal);
449458

450459
if (length > (poolSize - poolOffset))
451460
createPool();
461+
452462
let b = new FastBuffer(allocPool, poolOffset, length);
453463
const actual = ops.write(b, string, 0, length);
454464
if (actual !== length) {
455-
// byteLength() may overestimate. That's a rare case, though.
456465
b = new FastBuffer(allocPool, poolOffset, actual);
457466
}
467+
458468
poolOffset += actual;
459469
alignPool();
470+
460471
return b;
461472
}
462473

0 commit comments

Comments
 (0)