Array loop vs object loop lookup

JavaScript performance comparison

Revision 3 of this test case created by Jon-Carlos Rivera

Info

Which is better performance on large loops, Array indexes or object indexes?

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var the_array, the_object, i, len, result;
   
    the_array = [];
    the_object = {};
   
    for (i = 0; i< 10000; i++) {
      the_array.push("foobar");
      the_object["" + i] = "foobar";
    }
};
</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
Arrays
for (i = 0, len = the_array.length; i < len; i++) {
  result = the_array[i];
}
pending…
Objects
var k = Object.keys(the_object);

for (i = 0, len = k.length; i < len; i++) {
  result = the_object[k[i]];
}
 
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:

0 comments

Add a comment