for vs forEach (v162)

Revision 162 of this benchmark created by Joey Schooley on


Description

Is it faster to use the native forEach or just loop with for?

Takes into account the variables / functions required by each method.

Preparation HTML

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

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
values.forEach(function (val) {
   sum += val;
});
ready
for loop, uncached length
for (var j = 0; j < values.length; j++) {
 sum += values[j];
}
ready
for loop, cached length
for (var j = 0, l = values.length; j < l; j++) {
 sum += values[j];
}
ready
for loop, reverse, cached length, iteration statement
for (var l = values.length - 1; l >= 0; l--) {
 sum += values[l];
}
ready
for loop, reverse, cached length, no iteration statementmal reverse
for (var l = values.length; l--;) {
 sum += values[l];
}
ready
for in
for (var j in values) {
 sum += values[j];
}
ready
while loop, cached length
var l = values.length;
while (l--) {
 sum += values[l];
}
ready
while loop, cached length, no code block
var l = values.length;
while (l-- && (sum += values[l]));
ready
for loop, cached length, no code block (minimalist)
for (var l = values.length; l-- && (sum += values[l]););
ready

Revisions

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