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

JavaScript performance comparison

Revision 8 of this test case created

Info

Compare for loop performance.

Added QuickEach by James Padolsey : http://jsperf.com/jquery-each-vs-quickeach

Preparation code

<script src="https://raw.github.com/documentcloud/underscore/ba3e31b53ef5752b40cfb2d71f594536fefbe916/underscore-min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.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);
};

Benchmark.prototype.teardown = function() {
    no string concat
};
</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
var sum = 0;
var i = 0;
var length = array.length;

for (i; i < length; i++) {
  item = array[i];
  sum += item;
}
pending…
_.each
var sum = 0;

_.each(array, function(item) {
  return sum += item;
});
pending…
$.each
var sum = 0;

$.each(array, function() {
  return sum += this;
});
pending…
array.forEach
var sum = 0;

array.forEach(function(item) {
  return sum += item;
});
pending…
$.quickEach
var sum = 0;

$.quickEach(array, function() {
  return sum += this;
});
pending…
for with scope
var sum = 0;
var i = 0;
var length = array.length;

for (i; i < length; i++) {
  (function(i) {
    var item = array[i];
    sum += item;
  })(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