While vs For Queue

JavaScript performance comparison

Revision 46 of this test case created by Andreas Frömer

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…
Decremental For
for (; items.length;) {
  total += items.shift();
}
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:

1 comment

Andreas Frömer (revision owner) commented :

Simple explenation. I have tried some things to beat while, but technically it is impossible. "while" is considered only one condition while "for" has 3 parameter (which are all optional btw).

"do-while" is slowed down by the fact that it is always executing the body of the loop. To cut down the "for" loop to nearly as fast as "while" you have to use the same body and condition. A classic decremental "for" loop is still a bit slower because of the extra variable used.

Add a comment