for vs forEach (v84)

Revision 84 of this benchmark created on


Description

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

Inspired by Adrian Sutton's tests at: http://www.symphonious.net/2010/10/09/javascript-performance-for-vs-foreach/

This one adds random floating point numbers to see if the loop overhead is significant at all in the face of standard work.

Setup

var i = 0,
      value = 0,
      length = 100000,
      values = [],
      sum = 0,
      context = values;
    
    
    for (i = 0; i < length; i++) {
      values[i] = Math.random();
    }
    
    function add(val) {
      sum += val;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
forEach closure
values.forEach(function(val) {
  sum += val;
});
 
ready
while
i = 0
while(i < length){
  sum += values[i];
  i += 1;
}
 
ready
for ... in
for (i in values) {
  sum += values[i];
}
ready
forEach
values.forEach(add);
ready
for
for (i = 0; i < length; i += 1) {
  sum += values[i];
}
 
ready

Revisions

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