Fastest Loop

JavaScript performance comparison

Test case created by James Kyle

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
};
</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
For
for (var i = 0; i < a.length; i++) {}
pending…
For (cache length)
for (var i = 0, l = a.length; i < l; i++) {}
pending…
For (reverse)
for (var i = a.length; i--;) {}
pending…
For In
for (var i in a) {}
pending…
For (exists)
for (var i = 0; a[i]; i++) {}
pending…
While (imitate loop)
var i = 0; while (i < a.length) { i++; }
pending…
While (imitate loop) (cache length)
var i = 0, l = a.length; while (i < l) { i++; }
pending…
While (reverse)
var i = a.length; while (i--) {}
pending…
Do While (reverse)
var i = a.length - 1; do {} while (i--);
pending…
While (pop)
var i; while (i = a.pop()) {}
pending…
.forEach()
a.forEach(function() {});
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:

2 comments

Pomax commented :

Note: "For (exists)" wins only as long as the array has no gaps, and no content that can coerce to false (null, undefined, false, 0, and ""). So it's blazing fast but you need to be damn sure your array is filled with true-coercing data.

Pomax commented :

(in effect, the for(Exists) result should be divided by 10, as the very first check with i=0 gives a[i=0]==0 -> false, and so the loop terminates on the first check)

Add a comment