Loops

JavaScript performance comparison

Revision 115 of this test case created

Preparation code

<script>
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;
var i = arr.length;
while (i--) {
  console.log(i);
  z += 1;
};
pending…
Reverse while loop without implicit ToBoolean
var z = 0;
var i = arr.length;
while (i-- > 0) {
  console.log(i);
  z += 1;
};
pending…
Reverse do … while loop
var z = 0;
var i = arr.length;
do {
  console.log(i);
  z += 1;
} while (i--);
pending…
Reverse for loop
var z = 0;
for (var i = arr.length; i--;) {
  z += 1;
  console.log(i);
};
pending…
Old ’n’ busted for loop
var z = 0;
for (var i = 0; i < arr.length; ++i) {
  z += 1;
  console.log(i);
};
pending…
Old ’n’ busted for loop, caching the length
var z = 0;
for (var i = 0, len = arr.length; i < len; ++i) {
  z += 1;
  console.log(i);
};
pending…
Cool guy loop
var z = 0;
for (var i = -1; ++i < arr.length;) {
  z += 1;
  console.log(i);
};
pending…
Cool guy loop, caching the length
var z = 0;
for (var i = -1, len = arr.length; ++i < len;) {
  z += 1;
  console.log(i);
};
pending…
Native Array#forEach implementation
var z = 0;
arr.forEach(function(x) {
  z += x;
  console.log(z);
});
pending…
Native Array#forEach implementation with named function
var z = 0;

function foo(x) {
  z += x;
  console.log(z);
};
arr.forEach(foo);
pending…
Reverse while loop without implicit ToBoolean (2)
/* Joerg_Schaper@gmx.de 2013/06/16 */
var z = 0;
var i = arr.length;
while (i > 0) {
  z += 1;
  console.log(z);
  --i;
};
pending…
Reverse while loop without implicit ToBoolean (3)
/* Joerg_Schaper@gmx.de 2013/06/16 */
var z = 0;
var i = arr.length;
while (i > 0) {
  z += 1;
  console.log(z);
  i--;
};
pending…
var z = 0;
var i = arr.length;
while (--i > -1) {
  z += 1;
  console.log(z);
};
pending…
For .. in
var z = 0;
for (var i in arr) {
  z += 1;
  console.log(z);
};
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