Angular foreach vs Underscore foreach vs native For Loop vs reverse native for loop (v50)

Revision 50 of this benchmark created on


Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>


 <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
 <script src="http://underscorejs.org/underscore-min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.min.js"></script>

Setup

(function($) {
    
    // Create a placeholder jQuery object with a length of 1. The single item
    // is completely arbitrary and will be replaced.
    var jq = $([1]);
    
    $.fn.each2 = function( fn ) {
      var i = -1;
      
      while (
        // Set both the first element AND context property of the placeholder
        // jQuery object to the DOM element. When i has been incremented past the
        // end, this[++i] will return undefined and abort the while loop.
        ( jq.context = jq[0] = this[++i] )
        
        // Invoke the callback function in the context of the DOM element,
        // passing both the index and the placeholder jQuery object in. Like
        // .each, if the callback returns `false`, abort the while loop.
        && fn.call( jq[0], i, jq ) !== false
      ) {}
      
      // Return the initial jQuery object for chainability.
      return this;
    };
    
  })(jQuery);
  
  var sum = 0;
  var arr = [];
  var myFunc = function() {
    sum += 1;
  }
  for (var i = 0; i < 100000; i++) {
    arr.push(i)
  }

Test runner

Ready to run.

Testing in
TestOps/sec
angular foreach
angular.forEach(arr, myFunc);
ready
underscore foreach
_.each(arr, myFunc);
ready
for loop
for (var i = 0; i < arr.length; i++) {
  myFunc();
};
ready
for loop reverse
for (var i = arr.length - 1; i >= 0; i--) {
  myFunc();
};
ready
for loop with caching
for (var i = 0, len = arr.length; i < len; i++) {
  myFunc();
};
ready
browser forEach
arr.forEach(myFunc);
ready
jQuery .each
$.each(arr, myFunc);
ready
native for with caching and revered
for (var i = arr.length; i--;) {
  myFunc();
};
ready

Revisions

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