jQuery.fn.each vs. jQuery.fn.quickEach vs simpler stuff

JavaScript performance comparison

Revision 47 of this test case created by Andy Harman

Info

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:

Preparation code

<script src="//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>
<script>
Benchmark.prototype.setup = function() {
    var jq5;
};
</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
.each()
a.each(function() {
  $(this) //.css('width', '1px');
});
pending…
.quickEach()
a.quickEach(function() {
  this //.css('width', '1px'); // jQuery object
});
pending…
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
}
pending…
While loop
var jq = jQuery([1]),
    i = -1;
while (jq[0] = a[++i]) {
  jq //.css('width', '1px'); // jQuery object
}
pending…
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
}
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:

1 comment

Andy Harman (revision owner) commented :

This test is flawed. See revision 48 for better (faster) example.

Add a comment