Loop iteration (length comparison variations)

JavaScript performance comparison

Revision 9 of this test case created by Raymond

Info

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

Preparation code

<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/1.0.0-rc.3/lodash.min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    window.list = [];
    var x = 100;
    for (var y = 0; y < x; y++) {
      window.list[y] = true;
    }
};

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

  var fruit = window.list[i];
});
pending…
_.each
_.each(window.list, function (item) {

  var fruit = item;
});
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