jQuery.fn.each vs. jQuery.fn.quickEach vs simpler stuff (v47)

Revision 47 of this benchmark created by Andy Harman on


Description

The quickEach method will pass a non-unique jQuery instance to the callback meaning that there will be no need to instantiate a fresh jQuery instance on each iteration. Most of the slow-down inherent in jQuery’s native iterator method (each) is the constant need to have access to jQuery’s methods, and so most developers see constructing multiple instances as no issue… A better/alternative approach would be quickEach.

Notes:

  • The callback function is normally slower than each so the benefit of quickEach often isn't dramatic.

  • This version allows nesting of calls to quickEach (previous versions did not allow nesting).

  • Your callback function MUST NOT store the value of this to a closure variable (I accidentally did once - and it took me over an hour to track the problem down).

  • Using finally instead of catch seems to slow FireFox down.

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
  var a = $('<div/>').append(Array(100).join('<a></a>')).find('a');

  (function() {
    var jqx = [],
        level = -1;

    jQuery.fn.quickEach = function(c) {
      var jq = jqx[++level] || (jqx[level] = jQuery([1]));
      try {
        var i = -1,
            len = this.length;
        while (++i < len && c.call(jq, i, jq[0] = this[i]) !== false);
      } catch (e) {
        jq[0] = null;
        level--;
        throw e;
      }
      jq[0] = null;
      level--;
      return this;
    }
  })();
</script>

Setup

var jq5;

Test runner

Ready to run.

Testing in
TestOps/sec
.each()
a.each(function() {
  $(this) //.css('width', '1px');
});
ready
.quickEach()
a.quickEach(function() {
  this //.css('width', '1px'); // jQuery object
});
ready
For loop
//Note that this may be more suitable for your needs.
var jq = jQuery([1]);
for (var i = 0, len = a.length; i < len; i++) {
  jq[0] = a[i];
  jq //.css('width', '1px'); // jQuery object
}
ready
While loop
var jq = jQuery([1]),
    i = -1;
while (jq[0] = a[++i]) {
  jq //.css('width', '1px'); // jQuery object
}
ready
Reuse jq instance
//Re-use jq5 (jQuery constructor has non-trivial cost).
if (!jq5) {
  jq5 = jQuery([1]);
}
var i = -1;
while (jq5[0] = a[++i]) {
  jq5 //.css('width', '1px'); // jQuery object
}
ready

Revisions

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