Array.forEach vs for loop vs while loop vs lodash (v273)

Revision 273 of this benchmark created by Mike Smuin on


Description

Compare the performance between the following iterating mechanisms: Array.forEach, for loop (forward and reverse), while loop (forward and reverse), lodash library (_.each and _.eachRight)

Preparation HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>

Setup

// Initialize the base array
    var arr = [];
    for (var i = 0; i < 500; i++) {
      arr[i] = i;
    }
    var len = arr.length;
    
    // The function to be called on each iteration
    var iterateFunc = function(item, index) {
      return index + item * 3 * 8;
    };

Test runner

Ready to run.

Testing in
TestOps/sec
Array.forEach
arr.forEach(iterateFunc);
ready
Regular for loop
for (var i = 0; i < len; i++) {
  iterateFunc(arr[i], i);
}
ready
Funky for loop
for (var i = -1; ++i < len;) {
  iterateFunc(arr[i], i);
}
ready
While loop (internally used by lodash _.each)
var i = -1;

while (++i < len) {
  iterateFunc(arr[i], i);
}
ready
lodash _.each
_.each(arr, iterateFunc);
ready
Reverse regular for loop
for (var i = len - 1; i >= 0; i--) {
  iterateFunc(arr[i], i);
}
ready
Reverse funky for loop
for (var i = len; i--;) {
  iterateFunc(arr[i], i);
}
ready
Reverse while loop (internally used by lodash _.eachRight)
var i = len;
while (i--) {
  iterateFunc(arr[i], i);
}
ready
lodash _.eachRight
_.eachRight(arr, iterateFunc);
ready

Revisions

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