For vs While (v3)

Revision 3 of this benchmark created by Joshua Kehn on


Description

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 HTML

<script>
  var i, values = [],
      sum = 0;
  for (i = 0; i < 10000; i++) {
   values[i] = i;
  }
  
  function add(val) {
   sum += val;
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
ForEach
values.forEach(add);
ready
for loop, simple
for (i = 0; i < values.length; i++) {
 add(values[i]);
}
ready
for loop, cached length
var len = values.length;
for (i = 0; i < len; i++) {
 add(values[i]);
}
ready
for loop, reverse
for (i = values.length - 1; i >= 0; i--) {
 add(values[i]);
}
ready
for loop, cached length, no callback
var len = values.length;
for (i = 0; i < len; i++) {
 sum += values[i];
}
ready
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);
}
ready
While, reversed + simple
var i = values.length;
while (--i >= 0) {
 sum += values[i];
}
ready
While, reversed + complex callback
var i = values.length;
while (--i >= 0) {
 add.call(values, values[i], i, values);
}
ready
While, reversed, simple callback
var i = values.length;
while (--i >= 0) {
 add(values[i]);
}
ready
While, forwards, simple callback
var len = values.length,
    i = -1;
while (++i < len) {
 add(values[i]);
}
ready
While, reverse, simplified test
var l = values.length;
while (l--) {
 add(values[l]);
}
ready
While, reverse, simplified test, complex callback
var l = values.length;
while (l--) {
 add.call(values[l]);
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.