While vs For Queue

JavaScript performance comparison

Test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var items = [], total = 0, i = 0, j = 0;
    for(;i<100000;i++) {
      items[i] = Math.ceil( Math.random() * 10 );
    }
};
</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(; j<items.length; j++) {
  total += items[j];
}
pending…
While
while(items.length) {
  total += items.shift();
}
pending…
Do
do {
  total += items.shift();
} while(items.length);
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:

5 comments

Felix commented :

This test is invalid. You would need to either change the while loops to use a counter or change the for loop to be for(;items.length;){total+=items.shift();}

The shift call is not equivalent to items[j] with j++;

Douglas Muth commented :

I don't see this as a test of for vs while vs do, rather I see this as a test of for versus shift(). IMHO, using shift() to process a very large array is never a good idea, because removing an element from the front of the array could cause the array data structure to be re-created at a new location in memory each time shift() is called.

Contract with using for() and an integer (j) which is the current index in the array--in that case the array is effectively an immutable data structure and not altered in the least.

That said, seeing these pieces of code compared was still helpful, and may provide insight to programmers who are less experienced with Javascript. Thanks for writing the post.

Elf M. Sternberg commented :

I don't find this a correspondingly useful test. The while() loop is destructive to the sequence being analyzed; the for() loop is not.

Scott Koon commented :

I added a revision that hoists the items.length outside of the for loop. It did speed up a little bit. It's still not really close to the while loop.

Andreas Frömer commented :

I bet a decremental forloop is still the fastest.

So: var count = array.length; for(;count--;) { ... }

Add a comment