for vs forEach

JavaScript performance comparison

Revision 100 of this test case created

Info

Reduced elements due to stack overflow in some devices

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var i,
      value,
      length,
      values = [],
      sum = 0,
      context = values;
   
   
    for (i = 0; i < 2000; i++) {
      values[i] = Math.random();
    }
   
    function add(val) {
      sum += val;
    }
};

Benchmark.prototype.teardown = function() {
    i = 0;
    value = 0;
    length = 0;
    values = [];
    sum = 0;
};
</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
01. forEach
values.forEach(add);
pending…
02. for loop, simple
for (i = 0; i < values.length; i++) {
  sum += values[i];
}
pending…
03. for loop, cached length
length = values.length;
for (i = 0; i < length; i++) {
  sum += values[i];
}
pending…
04. for loop, reverse
for (i = values.length - 1; i >= 0; i--) {
  sum += values[i];
}
pending…
05. for loop, cached length, callback
length = values.length;
for (i = 0; i < length; i++) {
  add(values[i], i, values);
}
pending…
06. for loop, cached length, callback.call
length = values.length;
for (i = 0; i < length; i++) {
  add.call(context, values[i], i, values);
}
pending…
07. $.each
$.each(values, function(key, value) {
  sum += value;
});
pending…
08. for ... in
for (i in values) {
  sum += values[i];
}
pending…
09. for loop, reverse, decrement condition
for (i = values.length; i--;) {
  sum += values[i];
}
pending…
10. for loop, reverse, pre-decrement
for (i = values.length - 1; i >= 0; --i) {
  sum += values[i];
}
pending…
11. for loop, assignment condition
for (i = 0;
  (value = values[i]) !== undefined; i++) {
  sum += value;
}
pending…
12. for loop, assignment condition, reversed
for (i = values.length - 1;
  (value = values[i]) !== undefined; i--) {
  sum += value;
}
pending…
13. for loop, assignment condition, callback
for (i = 0;
  (value = values[i]) !== undefined; i++) {
  add(value, i, values);
}
pending…
14. for loop, assignment condition, callback.call
for (i = 0;
  (value = values[i]) !== undefined; i++) {
  add.call(context, value, i, values);
}
pending…
15. length cached as local var
var len;
for (i = 0, len = values.length; i < len; i++) {
  sum += values[i];
}
pending…
16. recursion loop
function addLoop(i) {
  if (i < values.length) {
    sum += values[i];
    addLoop(i + 1);
  }
}
addLoop(0);
pending…
16. reverse recursion
function addLoop(i) {
  if (i >= 0) {
    sum += values[i];
    addLoop(i - 1);
  }
}
addLoop(values.length - 1);
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