Iteration over objects vs arrays

JavaScript performance comparison

Revision 5 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.toString());
  }
  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.toString()] = i.toString();
  }
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>
<script>
Benchmark.prototype.setup = function() {
    count = 0;
};
</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++) {
 count += a1[i];
}
pending…
Iterate over object
for (i in ob) {
 count += i;
}
pending…
foreach
a1.forEach(function(v) {
 count += v;
});
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