Skip to content

Commit 44ee33f

Browse files
JacksonTianMyles Borins
authored and
Myles Borins
committed
buffer: refactor create buffer
Use createBuffer to reduce new Uint8Array() and setPrototypeOf. PR-URL: #4340 Reviewed-By: Michaël Zasso <[email protected]> Reviewed-By: Сковорода Никита Андреевич <[email protected]> Reviewed-By: Trevor Norris <[email protected]> Reviewed-By: Ben Noordhuis <[email protected]>
1 parent 901172a commit 44ee33f

File tree

1 file changed

+9
-11
lines changed

1 file changed

+9
-11
lines changed

lib/buffer.js

+9-11
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,17 @@ binding.setupBufferJS(Buffer.prototype, bindingObj);
1919
const flags = bindingObj.flags;
2020
const kNoZeroFill = 0;
2121

22+
function createBuffer(size) {
23+
const ui8 = new Uint8Array(size);
24+
Object.setPrototypeOf(ui8, Buffer.prototype);
25+
return ui8;
26+
}
2227

2328
function createPool() {
2429
poolSize = Buffer.poolSize;
2530
if (poolSize > 0)
2631
flags[kNoZeroFill] = 1;
27-
allocPool = new Uint8Array(poolSize);
28-
Object.setPrototypeOf(allocPool, Buffer.prototype);
32+
allocPool = createBuffer(poolSize);
2933
poolOffset = 0;
3034
}
3135
createPool();
@@ -67,9 +71,7 @@ function SlowBuffer(length) {
6771
length = 0;
6872
if (length > 0)
6973
flags[kNoZeroFill] = 1;
70-
const ui8 = new Uint8Array(+length);
71-
Object.setPrototypeOf(ui8, Buffer.prototype);
72-
return ui8;
74+
return createBuffer(+length);
7375
}
7476

7577
Object.setPrototypeOf(SlowBuffer.prototype, Uint8Array.prototype);
@@ -78,9 +80,7 @@ Object.setPrototypeOf(SlowBuffer, Uint8Array);
7880

7981
function allocate(size) {
8082
if (size === 0) {
81-
const ui8 = new Uint8Array(size);
82-
Object.setPrototypeOf(ui8, Buffer.prototype);
83-
return ui8;
83+
return createBuffer(size);
8484
}
8585
if (size < (Buffer.poolSize >>> 1)) {
8686
if (size > (poolSize - poolOffset))
@@ -95,9 +95,7 @@ function allocate(size) {
9595
// being zero filled.
9696
if (size > 0)
9797
flags[kNoZeroFill] = 1;
98-
const ui8 = new Uint8Array(size);
99-
Object.setPrototypeOf(ui8, Buffer.prototype);
100-
return ui8;
98+
return createBuffer(size);
10199
}
102100
}
103101

0 commit comments

Comments
 (0)