for vs while vs forEach (v355)

Revision 355 of this benchmark created by electron on


Description

The fastest syntax in for, forEach, and while.

Preparation HTML

<script>
var array = [],
    sum = 0,
    i = 0,
    length = 0;
array.length = 10000;
for (i = 0; i < array.length; i = (i + 1) | 0) {
  array[i] = i;
}
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
forEach, +=
array.forEach(function(v) {
  sum += v;
});
ready
forEach, sum + v
array.forEach(function(v) {
  sum = sum + v;
});
ready
forEach, recognize integer
array.forEach(function(v) {
  sum = (sum + v) | 0;
});
ready
for, no cache, increament is behind.
for (i = 0; i < array.length; i++) {
  sum += array[i];
}
ready
while, no cache, increament is behind.
while (i < array.length) {
  sum += array[i];
  i++;
}
ready
for, no cache, prelude increament
for (i = 0; i < array.length; ++i) {
  sum += array[i];
}
ready
while, no cache, prelude increament
while (i < array.length) {
  sum += array[i];
  ++i;
}
ready
while, no cache, prelude increament, recognize integer.
while (i < array.length) {
  sum = (sum + array[i]) | 0;
  i = (i + 1) | 0;
}
ready
while, no cache, prelude increament, recognize integer 2.
while (i < array.length) {
  sum += array[i];
  i = (i + 1) | 0;
}
ready
while, no cache, prelude increament, recognize integer 3.
while (i < array.length) {
  sum = (sum + array[i]) | 0;
  ++i;
}
ready
for, no cache, recognize integer.
for (i = 0; i < array.length; i = (i + 1) | 0) {
  sum = (sum + array[i]) | 0;
}
ready
for, cache, decrement is behind.
for (i = array.length - 1; 0 <= i; i--) {
  sum += array[i];
}
ready
while, cache, decrement is behind.
i = array.length - 1;
while (0 <= i) {
  sum += array[i];
  i--;
}
ready
for, prelude decrement
for (i = array.length - 1; 0 <= i; --i) {
  sum += array[i];
}
ready
while, prelude decrement
i = array.length - 1;
while (0 <= i) {
  sum += array[i];
  --i;
}
ready
for, cache length, increment is behind.
length = array.length;
for (i = 0; i < length; i++) {
  sum += array[i];
}
ready
while, cache length, increment is behind.
length = array.length;
while(i < length) {
  sum += array[i];
  i++;
}
ready
while, cache length, increment is behind, recognize integer.
length = array.length;
while(i < length) {
  sum = (sum + array[i]) | 0;
  i = (i + 1) | 0;
}
ready

Revisions

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