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

JavaScript performance comparison

Revision 23 of this test case created by master_zion

Info

Compare for loop performance.

Added a version of the CoffeeScript code where the window.array value is assigned to a local variable.

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;
   
    window.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…
CoffeeScript for loop, using local var
// string += item.toString() for item in array
var string = "";
var i = 0;
var array = window.array;
var length = array.length;

for (i; i < length; i++) {
  item = array[i];
  string += item.toString();
}
pending…
loop optimization
var string = "";
var i = 0;
var array = window.array;
var length = array.length;

for (i; i < length; i++) {
  string += array[i].toString();
}
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