Skip to content

Commit

Permalink
buffer: optimize createFromString
Browse files Browse the repository at this point in the history
PR-URL: #54324
  • Loading branch information
ronag committed Aug 12, 2024
1 parent 298ff4f commit ef035e4
Showing 1 changed file with 14 additions and 4 deletions.
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

Check failure on line 445 in lib/buffer.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Missing semicolon

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 ef035e4

Please sign in to comment.