Performance of Array vs. Object

JavaScript performance comparison

Revision 19 of this test case created by Jamie Olson

Info

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

variant of the original test - read only

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var data = {},arr = [], obj = {},
        i;
    for(i = 0; i < 100000; i += 1) {
        data[i] = {payload:i};
    }
   
    function getRandomIndex(obj) {
       var idx = Math.floor(Math.random()*99999);
       if(false === data.hasOwnProperty(idx)) {
          while (false === data.hasOwnProperty(idx)) {
              idx = Math.floor(Math.random()*9999);
          }
       }
       return idx;
    }
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Array Performance
var idx = getRandomIndex(data),
a = data[idx]

/*arr[idx] = a;
*/

 
pending…
Object Performance
var idx = getRandomIndex(data),
a = data[idx]

/*obj[idx] = a;
*/
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

1 comment

Jamie Olson (revision owner) commented :

Apparently, insertion into arrays and objects have pretty comparable performance.

Add a comment