Performance of Array vs. Object (v221)

Revision 221 of this benchmark created by bill on


Description

After seeing http://jsperf.com/javascript-associative-vs-non-associative-arrays, I thought the test could be improved.

I thought it was conspicuous that on Chrome, the Object iteration with known length was faster that a pure array (unlike in FireFox). The problem was the arr.length property was accessed on every iteration (and Firefox was optimizing it).

Setup

var arr = [],
        i,
        obj = {};
    for(i = 0; i < 10000; i += 1) {
        var o = {payload:i};
        arr.push(o);
        obj[i] = o;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Array Performance
var sum = 0;
var p=0
while(p=arr.shift()) {
    sum += p.payload;
}
ready
Object Performance
var sum = 0;
for (x in obj) {
    sum += obj[x].payload;
}
ready
Object Performance using known length
var sum = 0;
var p=0;
var x=-1;
while(p=obj[x++]) {
    sum += p.payload;
}
ready
Using Object.keys()
var sum = 0;
var keys = Object.keys(obj);
var kkk=keys.length;
for (var x=0; x<kkk; ++x) {
    sum += obj[keys[x]].payload
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.