-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path4-improved.js
More file actions
33 lines (25 loc) · 881 Bytes
/
4-improved.js
File metadata and controls
33 lines (25 loc) · 881 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
'use strict';
const poolify = (factory, { size, max }) => {
// It seems that preallocated array with defined size
// and using c-like for-loop will be more efficient in terms of V8 optimisation than
// const instances = new Array(size).fill(null).map(factory);
const instances = new Array(size);
for(let i = 0; i < size; i++){
instances[i] = factory();
}
const acquire = () => instances.pop() || factory();
const release = (instance) => {
if (instances.length < max) {
instances.push(instance);
}
};
return { acquire, release };
};
// Usage
const createBuffer = (size) => new Uint8Array(size);
const FILE_BUFFER_SIZE = 4096;
const createFileBuffer = () => createBuffer(FILE_BUFFER_SIZE);
const pool = poolify(createFileBuffer, { size: 10, max: 15 });
const instance = pool.acquire();
console.log({ instance });
pool.release(instance);