for vs forEach (v123)

Revision 123 of this benchmark created by Chen-Pang He on


Preparation HTML

<script>
  var i, values = [],
      sum = 0;
  for (i = 0; i < 10000; i++) {
   values[i] = i;
  }
  
  function add(val) {
   sum += val;
  }

Array.prototype.each = function (callback)
{
    for (var i = this.length - 1; i >= 0; i--)
        callback (this[i]);
}
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
values.forEach(add);
ready
Homemade each
values.each(add)
ready
For loop, queue
var len = values.length;
var sum = 0;
for (i = 0; i < len; i++) {
  sum += values[i];
}
ready
For loop, stack
var sum = 0;
for (var i = values.length - 1; i >= 0; i--) {
  sum += values[i];
}
ready

Revisions

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