for vs while vs forEach

JavaScript performance comparison

Revision 355 of this test case created by electron

Preparation code

<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

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
forEach, +=
array.forEach(function(v) {
  sum += v;
});
pending…
forEach, sum + v
array.forEach(function(v) {
  sum = sum + v;
});
pending…
while, no cache, increament is behind.
while (i < array.length) {
  sum += array[i];
  i++;
}
pending…
for, no cache, prelude increament
for (i = 0; i < array.length; ++i) {
  sum += array[i];
}
pending…
forEach, recognize integer
array.forEach(function(v) {
  sum = (sum + v) | 0;
});
pending…
for, no cache, increament is behind.
for (i = 0; i < array.length; i++) {
  sum += array[i];
}
pending…
while, cache length, increment is behind.
length = array.length;
while(i < length) {
  sum += array[i];
  i++;
}
pending…
while, no cache, prelude increament
while (i < array.length) {
  sum += array[i];
  ++i;
}
pending…
while, no cache, prelude increament, recognize integer.
while (i < array.length) {
  sum = (sum + array[i]) | 0;
  i = (i + 1) | 0;
}
pending…
while, no cache, prelude increament, recognize integer 2.
while (i < array.length) {
  sum += array[i];
  i = (i + 1) | 0;
}
pending…
while, no cache, prelude increament, recognize integer 3.
while (i < array.length) {
  sum = (sum + array[i]) | 0;
  ++i;
}
pending…
for, no cache, recognize integer.
for (i = 0; i < array.length; i = (i + 1) | 0) {
  sum = (sum + array[i]) | 0;
}
pending…
for, cache, decrement is behind.
for (i = array.length - 1; 0 <= i; i--) {
  sum += array[i];
}
pending…
while, cache, decrement is behind.
i = array.length - 1;
while (0 <= i) {
  sum += array[i];
  i--;
}
pending…
for, prelude decrement
for (i = array.length - 1; 0 <= i; --i) {
  sum += array[i];
}
pending…
for, cache length, increment is behind.
length = array.length;
for (i = 0; i < length; i++) {
  sum += array[i];
}
pending…
while, prelude decrement
i = array.length - 1;
while (0 <= i) {
  sum += array[i];
  --i;
}
pending…
while, cache length, increment is behind, recognize integer.
length = array.length;
while(i < length) {
  sum = (sum + array[i]) | 0;
  i = (i + 1) | 0;
}
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.

0 Comments