Iteration over objects vs arrays

JavaScript performance comparison

Revision 2 of this test case created

Info

Just testing the performace differences between iterating over an array and iterating over an object.

Preparation code

<script>
  var a1 = [],
      a2 = [],
      a3 = [],
      a4 = [],
      ob = {},
      collision = [];
 
  for (var i = 0; i < 5000; i++) {
   a1.push(i);
  }
  for (var i = 4000; i < 9000; i++) {
   a2.push(i);
  }
  for (var i = 0; i < 500000; i++) {
   a3.push(i);
  }
  for (var i = 400000; i < 900000; i++) {
   a4.push(i);
  }
  for (var i = 0; i < 5000; i++) {
   ob[i] = i;
  }
</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
Iterate over array
for (var i = 0; i < a1.length; i++) {
 a1[i] = i;
}
pending…
Iterate over object
for (var i in ob) {
 ob[i] = i;
}
pending…
Iterate over array using for..in
for each(var item in a1)
{
item = 0;
}
pending…
Standard collision test, medium array
for (var i = 0; i < a1.length; i++) {
 for (var o = 0; i < a2.length; i++) {
  if (a2[o] == a1[i]) collision.push(a1[i]);
 }
}
pending…
My collision test, medium array
var test = {};
for (var o in a1) {
 if (typeof a1[0] != 'Object') test[a1[o]] = a1[o];
 else test[a1[o]] = a1[o].join("_");
}
for (var o in a2) {
 if (test[a2[o]] !== undefined || (typeof a2[o] == 'Object' && test[a2[o].join("_")] !== undefined)) collision.push(a2[o]);
}
pending…
Standard collision test, giant array
for (var i = 0; i < a3.length; i++) {
 for (var o = 0; i < a4.length; i++) {
  if (a4[o] == a3[i]) collision.push(a3[i]);
 }
}
pending…
My collision test (modified), giant array
var test = {};
for (var o in a3) {
 test[a3[o]] = a3[o];
}
for (var o in a4) {
 if (test[a4[o]] !== undefined) collision.push(a4[o]);
}
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