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

JavaScript performance comparison

Revision 6 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.fn.quickEach = jQuery.quickEach = (function() {
   var jq = jQuery([1]);
   return function(c) {
    var i = -1,
        el, len = this.length;
    try {
     while (++i < len && (el = jq[0] = this[i]) && c.call(jq, i, el) !== false);
    } catch (e) {
     delete jq[0];
     throw e;
    }
    delete jq[0];
    return this;
   };
  }());
</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 = ""
for item in array
  string += item.toString()
*/

var item, string, _i, _len;

string = "";

for (_i = 0, _len = array.length; _i < _len; _i++) {
  item = array[_i];
  string += item.toString();
}
 
pending…
_.each
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 = "";

$(array).quickEach(function() {
  return string += this[0].toString();
});
pending…
while
var string = "";
var len = array.length;
var i = 0;
while (i < len) {
  string += array[i].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