Skip to content

Commit 50ae2ce

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

File tree

2 files changed

+22
-11
lines changed

2 files changed

+22
-11
lines changed

benchmark/buffers/buffer-from.js

Lines changed: 7 additions & 7 deletions
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

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -442,27 +442,38 @@ function allocate(size) {
442442
}
443443

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

447-
if (length >= (Buffer.poolSize >>> 1))
448+
if (stringLength > poolLength)
449+
return createFromString(string, ops.encodingVal);
450+
451+
let length = stringLength * 4; // max utf8 byte length
452+
453+
if (length >= poolLength)
454+
length = ops.byteLength(string);
455+
456+
if (length >= poolLength)
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

463474
function fromString(string, encoding) {
464475
let ops;
465-
if (typeof encoding !== 'string' || encoding.length === 0) {
476+
if (typeof encoding !== 'string' || encoding === 'utf8' || encoding.length === 0) {
466477
if (string.length === 0)
467478
return new FastBuffer();
468479
ops = encodingOps.utf8;

0 commit comments

Comments
 (0)