for vs forEach (v100)

Revision 100 of this benchmark created on


Description

Reduced elements due to stack overflow in some devices

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>

Setup

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

Teardown


    i = 0;
    value = 0;
    length = 0;
    values = [];
    sum = 0;
  

Test runner

Ready to run.

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

Revisions

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