While vs For Queue

JavaScript performance comparison

Test case created

Preparation code

Benchmark.prototype.setup = function() {
    var items = [], total = 0, i = 0, j = 0;
    for(;i<100000;i++) {
      items[i] = Math.ceil( Math.random() * 10 );

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(; j<items.length; j++) {
  total += items[j];
while(items.length) {
  total += items.shift();
do {
  total += items.shift();
} while(items.length);

Compare results of other browsers


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:


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--;) { ... }

Comment form temporarily disabled.

Add a comment