Array.forEach vs for loop vs while loop vs lodash

JavaScript performance comparison

Revision 273 of this test case created by Mike Smuin

Preparation code

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
      
<script>
Benchmark.prototype.setup = function() {
  // 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;
  };

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Array.forEach
arr.forEach(iterateFunc);
pending…
Regular for loop
for (var i = 0; i < len; i++) {
  iterateFunc(arr[i], i);
}
pending…
Funky for loop
for (var i = -1; ++i < len;) {
  iterateFunc(arr[i], i);
}
pending…
While loop (internally used by lodash _.each)
var i = -1;

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

0 Comments