CoffeeScript's for vs. Underscore _.each vs. jQuery $.each (v26)

Revision 26 of this benchmark created by DeLaGuardo on


Description

Compare for loop performance.

The previous version of this test set the global array variable used in the tests as window.array. This test instead declare this variable as var array. This has a significant effect on the results of the tests. The previous version showed the CoffeeScript-generated code to be slower than the lodash code. This version of the test shows that the CoffeeScript-generated code is the fastest.

The reason for this is that accessing array if the VM has to resolve it to window.array is slower than accessing array if it has been defined with var. So the CoffeeScript-generated code would be at a disadvantage relative to lodash since lodash grabs a reference to array once whereas the CoffeeScript code refers to it on each iteration.

Preparation HTML

<script src="https://rawgithub.com/lodash/lodash/2.2.1/dist/lodash.min.js">
</script>
<script src="https://code.jquery.com/jquery-2.0.3.min.js">
</script>
<script>
jQuery.quickEach = (function() {
 return function(arr, c) {
  var i = -1,
      el, len = arr.length;
  try {
   while (++i < len && (el = arr[i]) && c.call(el, i, el) !== false);
  } catch (e) {
   throw e;
  }
 };
}());
</script>

Setup

var _i, _results;
    
    var array = (function() {
      _results = [];
      for (_i = 1; _i <= 1000; _i++) {
        _results.push(_i);
      }
      return _results;
    }).apply(this);

Test runner

Ready to run.

Testing in
TestOps/sec
CoffeeScript for loop
// string += item.toString() for item in array
var string = "";
var i = 0;
var length = array.length;

for (i; i < length; i++) {
  item = array[i];
  string += item.toString();
}
ready
_.each / Lodash
var string = "";

_.each(array, function(item) {
  return string += item.toString();
});
ready
$.each
var string = "";

$.each(array, function() {
  return string += this.toString();
});
ready
array.forEach
var string = "";

array.forEach(function(item) {
  return string += item.toString();
});
ready
$.quickEach
var string = "";

$.quickEach(array, function() {
  return string += this.toString();
});
ready
for with scope
// string += item.toString() for item in array
var string = "";
var i = 0;
var length = array.length;

for (i; i < length; i++) {
  (function(i) {
    var item = array[i];
    string += item.toString();
  })(i);
}
ready
real coffee for loop
// string += item.toString() for item in array
var string = "";
var i = 0;
var length = array.length;

var results = []
for (i; i < length; i++) {
  item = array[i];
  results.push(string += item.toString());
}
ready
Latest coffee version
var string = "";
var item, _i, _len;

for (_i = 0, _len = array.length; _i < _len; _i++) {
  item = array[_i];
  string += item.toString();
}
ready

Revisions

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