Skip to content

Commit f37d0cd

Browse files
committed
buffer: add bufferPool to Buffer.of
1 parent 6176222 commit f37d0cd

File tree

2 files changed

+40
-4
lines changed

2 files changed

+40
-4
lines changed

benchmark/buffers/buffer-of.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
'use strict';
2+
3+
const common = require('../common.js');
4+
5+
// Measure Buffer.of(...items) throughput for various lengths.
6+
// We prebuild the items array to avoid measuring array construction,
7+
// and vary the effective iterations with length to keep total work reasonable.
8+
9+
const bench = common.createBenchmark(main, {
10+
len: [0, 1, 8, 64, 256, 1024],
11+
n: [5e5],
12+
});
13+
14+
function main({ len, n }) {
15+
const items = new Array(len);
16+
for (let i = 0; i < len; i++) items[i] = i & 0xFF;
17+
18+
bench.start();
19+
for (let i = 0; i < n; i++) {
20+
Buffer.of(...items);
21+
}
22+
bench.end(n);
23+
}

lib/buffer.js

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -382,10 +382,23 @@ Buffer.copyBytesFrom = function copyBytesFrom(view, offset, length) {
382382
// Refs: https://tc39.github.io/ecma262/#sec-%typedarray%.of
383383
// Refs: https://esdiscuss.org/topic/isconstructor#content-11
384384
const of = (...items) => {
385-
const newObj = createUnsafeBuffer(items.length);
386-
for (let k = 0; k < items.length; k++)
387-
newObj[k] = items[k];
388-
return newObj;
385+
const len = items.length;
386+
if (len === 0) return new FastBuffer();
387+
if (len < (Buffer.poolSize >>> 1)) {
388+
if (len > (poolSize - poolOffset))
389+
createPool();
390+
const b = new FastBuffer(allocPool, poolOffset, len);
391+
for (let k = 0; k < len; k++)
392+
b[k] = items[k];
393+
poolOffset += len;
394+
alignPool();
395+
return b;
396+
}
397+
398+
const b = createUnsafeBuffer(len);
399+
for (let k = 0; k < len; k++)
400+
b[k] = items[k];
401+
return b;
389402
};
390403
Buffer.of = of;
391404

0 commit comments

Comments
 (0)