CoffeeScript's for vs. Underscore _.each vs. jQuery $.each

JavaScript performance comparison

Revision 21 of this test case created by Louis Dubeau

Info

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 code

<script src="//rawgithub.com/lodash/lodash/2.2.1/dist/lodash.min.js">
</script>
<script src="//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>
<script>
Benchmark.prototype.setup = function() {
    var _i, _results;
   
    var array = (function() {
      _results = [];
      for (_i = 1; _i <= 1000; _i++) {
        _results.push(_i);
      }
      return _results;
    }).apply(this);
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/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();
}
pending…
_.each / Lodash
var string = "";

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

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

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

$.quickEach(array, function() {
  return string += this.toString();
});
pending…
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);
}
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. Here’s a list of current revisions for this page:

0 comments

Add a comment