Loop iteration (length comparison variations)

JavaScript performance comparison

Revision 11 of this test case created

Info

Comparison of different ways to treat the length of an array when iterating the array.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    window.list = [];
    var x = 100;
    for (var y = 0; y < x; y++) {
      window.list[y] = {a: y, b: "abc" + y};
    }
   
    window.forEach = function (list, fn) {
      var item, list = list.slice(0);
      while (item = list.pop()) {
        fn(item);
      }
    }
};

Benchmark.prototype.teardown = function() {
    delete window.list;
};
</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
Using list.length
for (var i = 0; i < window.list.length; i++) {
  var fruit = window.list[i];
  fruit.a += 1;
}
pending…
Using static len - outside for declr.
var len = window.list.length;
for (var i = 0; i < len; i++) {
  var fruit = window.list[i];
  fruit.a += 1;
}
pending…
Using static len - inside for declr.
for (var i = 0, len = window.list.length; i < len; i++) {
  var fruit = window.list[i];
  fruit.a += 1;
}
pending…
Reverse Loop (for)
for (var i = window.list.length; i--;) {
  var fruit = window.list[i];
  fruit.a += 1;
}
pending…
Reverse Loop (while)
var i = window.list.length;
while (i--) {
  var fruit = window.list[i];
  fruit.a += 1;
}
pending…
Reverse Loop (for) w/ outside declaration & --
var i = window.list.length;
for (; i--;) {
  var fruit = window.list[i];
  fruit.a += 1;
}
pending…
Reverse Loop (for) w/ outside declaration & >= 0
var i = window.list.length,
    fruit;
for (; i >= 0; i--) {
  fruit = window.list[i];
  fruit.a += 1;
}
pending…
Destructive array - shift
var list = window.list.slice(0),
    fruit = list.shift();
while (fruit) {
  fruit.a += 1;
  fruit = list.shift();
}
pending…
Destructive array - pop
var list = window.list.slice(0),
    fruit = list.pop();
while (fruit) {
  fruit.a += 1;
  fruit = list.pop();
}
pending…
Destructive array - pop w/ reverse
var list = window.list.slice(0).reverse(),
    fruit = list.pop();
while (fruit) {
  fruit.a += 1;
  fruit = list.pop();
}
pending…
Destructive array - pop 2
window.forEach(window.list, function (item) { item.a += 1; });
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