JavaScript Loops

JavaScript performance comparison

Test case created by Elijah Manor

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var arr = new Array(800);
    for (var i = 0; i < arr.length; ++i) arr[i] = Math.random() * 1000;
};
</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 Cached
var i = 0,
    arrLength = arr.length;
while (i < arrLength) {
  arr[i] += i;
  i++;
}
pending…
Reverse While Loop
var i = arr.length;
while (i--) {
  arr[i] += i;
}
pending…
Old and Busted
for (var i = 0; i < arr.length; ++i) {
  arr[i] += i;
}
pending…
Old and Busted Cached
var arrLength = arr.length;
for (var i = 0; i < arrLength; ++i) {
  arr[i] += i;
}
pending…
Cool Guy Loop
for (var i = -1, len = arr.length; ++i < len;) {
  arr[i] += i;
}
pending…
Cool Guy Loop Cached
var arrLength = arr.length;
for (var i = -1, len = arrLength; ++i < len;) {
  arr[i] += i;
}
pending…
Reversed Reverse While Loop
arr.reverse();
var i = arr.length;
while (i--) {
  arr[i] += i;
}
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment