Skip to content

Commit 4be82f6

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

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

lib/buffer.js

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -150,11 +150,12 @@ const constants = ObjectDefineProperties({}, {
150150
});
151151

152152
Buffer.poolSize = 8 * 1024;
153-
let poolSize, poolOffset, allocPool;
153+
let poolSize, poolOffset, allocPool, allocBuffer;
154154

155155
function createPool() {
156156
poolSize = Buffer.poolSize;
157-
allocPool = createUnsafeBuffer(poolSize).buffer;
157+
allocBuffer = createUnsafeBuffer(poolSize);
158+
allocPool = allocBuffer.buffer;
158159
markAsUntransferable(allocPool);
159160
poolOffset = 0;
160161
}
@@ -442,27 +443,35 @@ function allocate(size) {
442443
}
443444

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

447-
if (length >= (Buffer.poolSize >>> 1))
448+
let length = string.length; // Min length
449+
450+
if (length >= maxLength)
451+
return createFromString(string, ops.encodingVal);
452+
453+
length *= 4; // Max length (4 bytes per character)
454+
455+
if (length >= maxLength)
456+
length = ops.byteLength(string); // Actual length
457+
458+
if (length >= maxLength)
448459
return createFromString(string, ops.encodingVal);
449460

450461
if (length > (poolSize - poolOffset))
451462
createPool();
452-
let b = new FastBuffer(allocPool, poolOffset, length);
453-
const actual = ops.write(b, string, 0, length);
454-
if (actual !== length) {
455-
// byteLength() may overestimate. That's a rare case, though.
456-
b = new FastBuffer(allocPool, poolOffset, actual);
457-
}
463+
464+
const actual = ops.write(allocBuffer, string, poolOffset, length);
465+
const b = new FastBuffer(allocPool, poolOffset, actual);
466+
458467
poolOffset += actual;
459468
alignPool();
460469
return b;
461470
}
462471

463472
function fromString(string, encoding) {
464473
let ops;
465-
if (typeof encoding !== 'string' || encoding.length === 0) {
474+
if (!encoding || encoding === 'utf8') {
466475
if (string.length === 0)
467476
return new FastBuffer();
468477
ops = encodingOps.utf8;

0 commit comments

Comments
 (0)