Wednesday, 31 May 2017

Array and object performance in Javscript benchmarked

I was curies and extended the test of arr vs obj and actually accessed the object properties. The results are confusing to me, check the benchmark yourself.

The code

var a1 = [{id: 29938, name: 'name1'}, {id: 32994, name: 'name2'}];

var a2 = [];
// a2[0] = {id: 29938, name: 'name1'}; // no significant time diff to push
// a2[2] = {id: 32994, name: 'name2'};
a2.push( {id: 29938, name: 'name1'});
a2.push( {id: 32994, name: 'name2'});

var o = {};
o['0'] = {id: 29938, name: 'name1'};
o['1'] = {id: 32994, name: 'name2'};

var o2 = {};
o2['foo'] = {id: 29938, name: 'name1'};
o2['bar'] = {id: 32994, name: 'name2'};

for (var i = 0; i < 1e6; i++) {
  var foo = 0;
  foo = a1[0].id;
  foo = a1[1].id;
}

for (var i = 0; i < 1e6; i++) {
  var foo = 0;
  foo = a2[0].id;
  foo = a2[1].id;
}

for (var i = 0; i < 1e6; i++) {
  var foo = 0;
  foo = o['0'].id;
  foo = o['1'].id;
}

for (var i = 0; i < 1e6; i++) {
  var foo = 0;
  foo = o2['foo'].id;
  foo = o2['bar'].id;
}

Why is the array a1 directly initialized so slow?
Why do the results differ so much under nodejs (changing relation, not sys. offset), with a significant increase in the index-numbered object o, I would expect o2:

$ node test.js 
dbsave: 31.543ms
dbsave: 6.002ms
dbsave: 35.349ms
dbsave: 6.107ms



via ItsmeJulian

No comments:

Post a Comment