Iteration over objects vs arrays

JavaScript performance comparison

Revision 3 of this test case created by Tim

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;
  }

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};
</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 array deleting every 5th item
for (var i = 0; i < a1.length; i++) {
 if (i % 5 == 0) {
   a1.remove(i);
 }
}
pending…
Iterate over array creating new one without every 5th
a2 = [];
for (var i = 0; i < a1.length; i++) {
 if (i % 5 != 0) {
   a2.push(a1[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