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

JavaScript performance comparison

Revision 47 of this test case created by Andy Harman


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.


Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
  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;
        throw e;
      jq[0] = null;
      return this;
Benchmark.prototype.setup = function() {
    var jq5;

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
a.each(function() {
  $(this) //.css('width', '1px');
a.quickEach(function() {
  this //.css('width', '1px'); // jQuery object
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
While loop
var jq = jQuery([1]),
    i = -1;
while (jq[0] = a[++i]) {
  jq //.css('width', '1px'); // jQuery object
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

Compare results of other browsers


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.

Comment form temporarily disabled.

Add a comment