For vs While

JavaScript performance comparison

Revision 3 of this test case created by Joshua Kehn

Info

Simplified conditions to demonstrate that while concise it rarely offers a speed improvement. Code readability is improved with a condition (and will allow you to traverse forward on an array instead of straight down) and no loss of speed.

Preparation code

<script>
  var i, values = [],
      sum = 0;
  for (i = 0; i < 10000; i++) {
   values[i] = i;
  }
 
  function add(val) {
   sum += val;
  }
</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
ForEach
values.forEach(add);
pending…
for loop, simple
for (i = 0; i < values.length; i++) {
 add(values[i]);
}
pending…
for loop, cached length
var len = values.length;
for (i = 0; i < len; i++) {
 add(values[i]);
}
pending…
for loop, reverse
for (i = values.length - 1; i >= 0; i--) {
 add(values[i]);
}
pending…
for loop, cached length, no callback
var len = values.length;
for (i = 0; i < len; i++) {
 sum += values[i];
}
pending…
for loop, cached length, using function.call and supplying index and original array
var len = values.length;
for (i = 0; i < len; i++) {
 add.call(values, values[i], i, values);
}
pending…
While, reversed + simple
var i = values.length;
while (--i >= 0) {
 sum += values[i];
}
pending…
While, reversed + complex callback
var i = values.length;
while (--i >= 0) {
 add.call(values, values[i], i, values);
}
pending…
While, reversed, simple callback
var i = values.length;
while (--i >= 0) {
 add(values[i]);
}
pending…
While, forwards, simple callback
var len = values.length,
    i = -1;
while (++i < len) {
 add(values[i]);
}
pending…
While, reverse, simplified test
var l = values.length;
while (l--) {
 add(values[l]);
}
pending…
While, reverse, simplified test, complex callback
var l = values.length;
while (l--) {
 add.call(values[l]);
}
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:

0 comments

Add a comment