Skip to content

Commit 436d9c8

Browse files
committed
buffer: optimize createFromString
PR-URL: nodejs#54324
1 parent 298ff4f commit 436d9c8

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

lib/buffer.js

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

444444
function fromStringFast(string, ops) {
445-
const length = ops.byteLength(string);
445+
const stringLength = string.length;
446446

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

450458
if (length > (poolSize - poolOffset))
451459
createPool();
460+
452461
let b = new FastBuffer(allocPool, poolOffset, length);
453462
const actual = ops.write(b, string, 0, length);
454463
if (actual !== length) {
455-
// byteLength() may overestimate. That's a rare case, though.
456464
b = new FastBuffer(allocPool, poolOffset, actual);
457465
}
466+
458467
poolOffset += actual;
459468
alignPool();
469+
460470
return b;
461471
}
462472

463473
function fromString(string, encoding) {
464474
let ops;
465-
if (typeof encoding !== 'string' || encoding.length === 0) {
475+
if (typeof encoding !== 'string' || encoding === 'utf8' || encoding.length === 0) {
466476
if (string.length === 0)
467477
return new FastBuffer();
468478
ops = encodingOps.utf8;

0 commit comments

Comments
 (0)