for-loop-tests

JavaScript performance comparison

Revision 2 of this test case created by Scott

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var arr = new Array(100);
    for (var j = 0, n = arr.length; j < n; j++) {
      arr[j] = Math.random();
    }
};
</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
while loop that imitates a for loop
var z = 0;
var i = 0;
while (i < arr.length) {
  z += 1;
  console.log(i);
  i++;
};
pending…
while loop that imitates a for loop, caching the length
var z = 0;
var i = 0,
  len = arr.length;
while (i < len) {
  z += 1;
  console.log(i);
  i++;
};
pending…
Reverse while loop
var z = 0;
arr.reverse();
var i = arr.length;
while (i--) {
  console.log(i);
  z += 1;
};
pending…
Reverse do … while loop
var z = 0;
arr.reverse();
var i = arr.length;
while (i-- > 0) {
  console.log(i);
  z += 1;
};
pending…
Reverse for loop
var z = 0;
arr.reverse();
for (var i = arr.length; i--;) {
  z += 1;
  console.log(i);
};
pending…
Reverse for loop with ~
var z = 0;
arr.reverse();
for (var i = arr.length;~ i; i--) {
  z += 1;
  console.log(i);
};
pending…
'Normal' for loop
var z = 0;
for (var i = 0, len = arr.length; i < len; ++i) {
  z += 1;
  console.log(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