for vs forEach vs loop

JavaScript performance comparison

Revision 140 of this test case created by Daniel Ostrovsky

Preparation code

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.1/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.3.1/lodash.min.js"></script>
<script>
var lodash = _.noConflict();
</script>
      
<script>
Benchmark.prototype.setup = function() {
  var _ = window._,
    angular = window.angular,
    lodash = window.lodash;
  
  var arr = [];
  var _set = new Set();
  for (var i = 0; i < 100000; i++) {
    arr[i] = {
      val: i,
      bool: Boolean((i % 3))
    };
    _set.add(Boolean((i % 3)))
  }
  
  var values = [];
  var _sets = [];

};
</script>

Preparation code output

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.5/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.3.1/lodash.min.js"></script> <script> var lodash = _.noConflict(); </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(function(value) {
  if (value.bool) {
    values.push(value.val);
  }
});
pending…
underscore.forEach
_.forEach(arr, function(value) {
  if (value.bool) {
    values.push(value.val);
  }
});
pending…
lodash.forEach
lodash.forEach(arr, function(value) {
  if (value.bool) {
    values.push(value.val);
  }
});
pending…
angular.forEach
angular.forEach(arr, function(value) {
  if (value.bool) {
    values.push(value.val);
  }
});
pending…
standard for
for (var i = 0, l = arr.length; i < l; i++) {
  if (arr[i].bool) {
    values.push(arr[i].val);
  }
}
pending…
Sets
'use strict'
for (let val of _set) {
  if (val.bool) {
    _sets.push(val)
  }
}
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