Skip to content

Commit fae367b

Browse files
subzeyMyles Borins
authored and
Myles Borins
committed
lib: freelist: use .pop() for allocation
Array#pop() is known to be faster than Array#shift(). To be exact, it's O(1) vs. O(n). In this case there's no difference from which side of the "pool" array the object is retrieved, so .pop() should be preferred. PR-URL: #2174 Reviewed-By: mscdex - Brian White <[email protected]> Reviewed-By: jasnell - James M Snell <[email protected]> Reviewed-By: ofrobots - Ali Ijaz Sheikh <[email protected]>
1 parent 788aa45 commit fae367b

File tree

3 files changed

+41
-3
lines changed

3 files changed

+41
-3
lines changed

benchmark/misc/freelist.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
'use strict';
2+
3+
var common = require('../common.js');
4+
var FreeList = require('internal/freelist').FreeList;
5+
6+
var bench = common.createBenchmark(main, {
7+
n: [100000]
8+
});
9+
10+
function main(conf) {
11+
var n = conf.n;
12+
var poolSize = 1000;
13+
var list = new FreeList('test', poolSize, Object);
14+
var i;
15+
var j;
16+
var used = [];
17+
18+
// First, alloc `poolSize` items
19+
for (j = 0; j < poolSize; j++) {
20+
used.push(list.alloc());
21+
}
22+
23+
bench.start();
24+
25+
for (i = 0; i < n; i++){
26+
// Return all the items to the pool
27+
for (j = 0; j < poolSize; j++) {
28+
list.free(used[j]);
29+
}
30+
31+
// Re-alloc from pool
32+
for (j = 0; j < poolSize; j++) {
33+
list.alloc();
34+
}
35+
}
36+
37+
bench.end(n);
38+
}

lib/internal/freelist.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ exports.FreeList = function(name, max, constructor) {
1010

1111

1212
exports.FreeList.prototype.alloc = function() {
13-
return this.list.length ? this.list.shift() :
13+
return this.list.length ? this.list.pop() :
1414
this.constructor.apply(this, arguments);
1515
};
1616

test/parallel/test-freelist.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,6 @@ assert.strictEqual(flist1.free('test4'), false);
2929
assert.strictEqual(flist1.free('test5'), false);
3030

3131
// At this point 'alloc' should just return the stored values
32-
assert.strictEqual(flist1.alloc(), 'test1');
33-
assert.strictEqual(flist1.alloc(), 'test2');
3432
assert.strictEqual(flist1.alloc(), 'test3');
33+
assert.strictEqual(flist1.alloc(), 'test2');
34+
assert.strictEqual(flist1.alloc(), 'test1');

0 commit comments

Comments
 (0)