For loop v.s. native forEach

JavaScript performance comparison

Revision 5 of this test case created

Info

Try to find out which one is more efficient.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var array = [],
        i = 0,
        j = 0,
        result1 = 0,
        result2 = 0,
        result3 = 0,
        plus = function(item) {
        result1 += item;
        };
    Array.prototype.foreach = function(func) {
      var k = 0;
      for (k = 0; k < this.length; k += 1) {
        func.call(this, this[k], k);
      }
    }
   
    for (i = 0; i < 10000; i += 1) {
      array[i] = i;
    }
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
For loop
for (j = 0; j < array.length; j += 1) {
  plus.call(this, array[j]);
}
pending…
Native forEach
array.forEach(function(item) {
  result2 += item;
});
pending…
Added foreach
array.foreach(function(item) {
  result3 += item;
});
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. Here’s a list of current revisions for this page:

0 comments

Add a comment