jQuery each2 plugin vs .each$ plugin vs jQuery core .each method (v16)

Revision 16 of this benchmark created by Jason DiMeo on


Description

Basically, if you're going to do $(this) inside an .each loop, you should consider using the jQuery each2 plugin instead, because it's specifically optimized for this extremely common use case!

For whatever reason, the modifications I made are even faster. The reason I even attempted to modify Ben's code was that the this reference was not accurate in some instances.

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<!-- the plugin -->
<script src="http://github.com/cowboy/jquery-misc/raw/master/jquery.ba-each2.js"></script>

<script>
jQuery.fn.extend({
  each$: function(fn) {
    var $elem = jQuery([1]);
    try {
      for (var i = 0; i < this.length; i++) {
        if (fn.call(jQuery.context = $elem[0] = this[i], i, $elem) === false) { break; }
      }
    } finally {
      delete $elem[0];
    }
    return this;
  }
});
  // Create a whole bunch of elements for iteration.
  var elems = $('<div/>').append(Array(1000).join('<span/>')).children();
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
jQuery each2 plugin
elems.each2(function(i, jq) {
 this; // DOM element
 jq; // jQuery object
});
ready
jQuery core .each method
elems.each(function(i, elem) {
 this; // DOM element
 $(this); // jQuery object
});
ready
jQuery each$ plugin
elems.each$(function(i, $elem) {
 this; // DOM element
 $elem; // jQuery object
});
ready

Revisions

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