我想确定javascript中小树节点的最佳结构。每个节点都有键,值和对父节点和子节点的引用(如果存在)。所以我编写了测试节点创建性能的基准:
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite();
suite
.add('Object node creation', function() {
var parent = {
key: 'some_key',
value: 1234123412,
parent: null,
left: null,
right: null
};
var left = {
key: 'left child',
value: 'asdfoasjdfpasdjf',
parent: null,
left: null,
right: null
};
var right = {
key: 'right child',
value: 'qwerqwerqwerqwwq',
parent: null,
left: null,
right: null
};
parent.left = left;
parent.right = right;
left.parent = parent;
right.parent = parent;
})
.add('Array node creation', function() {
var parent = ['some_key', 1234123412, null, null, null];
var left = ['left_child', 'asdfoasjdfpasdjf', null, null, null];
var right = ['right_child', 'qwerqwerqwerqwwq', null, null, null];
parent[3] = left;
parent[4] = right;
left[2] = parent;
right[2] = parent;
})
.on('complete', function() {
console.log(this[0].toString());
console.log(this[1].toString());
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
.run();
所以我运行测试:
node benchmark.js
并得到以下结果:
Object node creation x 30,613,857 ops/sec ±3.11% (82 runs sampled)
Array node creation x 15,133,139 ops/sec ±1.12% (94 runs sampled)
Fastest is Object node creation
没关系。
然后我用--debug-brk运行基准:
node --debug-brk benchmark.js
并获得以下结果:
Object node creation x 4,842,367 ops/sec ±2.81% (90 runs sampled)
Array node creation x 10,906,219 ops/sec ±2.36% (90 runs sampled)
Fastest is Array node creation
如您所见:对象创建的性能急剧下降。 也许有人可以解释我为什么会这样以及发生了什么。