I want to decide what is best structure in javascript for small tree nodes. Each node have key, value and references to the parent and child nodes (if exists). So I wrote benchmark for testing performance of the nodes creation:
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();
So I run the test:
node benchmark.js
and have the following results:
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
And it's OK.
But then I run benchmark with --debug-brk:
node --debug-brk benchmark.js
and get the following results:
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
As you see: performance of object creation was decreased drastically. Maybe someone can explain me why it so and what is happened.