for vs. forEach with anonymous functions

Benchmark created on


Description

Which loop is better at handling anonymous inner functions?

Preparation HTML

<div id="test">
</div>

Setup

var values = [];
    var sum = 0;
    
    for (i = 0; i < 10000; i++) {
      values[i] = i;
    }
    
    function add(value) {
      sum += value;
    };
    
    function addAttribute(value) {
      var div = document.getElementById("test");
      div.setAttribute("value", value);
    };

Test runner

Ready to run.

Testing in
TestOps/sec
For, cached length
for (var i = 0, len = values.length; i < len; i++) {
  (function(value) {
    sum += value;
  })(i);
}
ready
ForEach
values.forEach(function(value) {
  sum += value;
});
ready
For, modify DOM
for (var i = 0, len = values.length; i < len; i++) {
  (function(value) {
    var div = document.getElementById("test");
    div.setAttribute("value", value);
  })(i);
}
ready
ForEach, modify DOM
values.forEach(function(value) {
  var div = document.getElementById("test");
  div.setAttribute("value", value);
});
ready
For, cached inner function
for (var i = 0, len = values.length; i < len; i++) {
  add(i);
}
ready
ForEach, cached inner function
values.forEach(function(value) {
  add(value)
});
ready
For, cached DOM manip
for (var i = 0, len = values.length; i < len; i++) {
  addAttribute(i);
}
ready
ForEach, cached DOM manip
values.forEach(function(value) {
  addAttribute(value)
});
ready

Revisions

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