jQuery each2 plugin vs jQuery core .each method (v44)

Revision 44 of this benchmark created 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!

Preparation HTML

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

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

<script>
  // 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) {
  jq; // Use at will!
  jq; // No performance penalty.
  jq; // No performance penalty.
});
ready
jQuery core .each method
elems.each(function(i, elem) {
  var jq = $(this); // This is the best we can do here.
  jq; // No performance penalty.
  jq; // No performance penalty.
  jq; // No performance penalty.
});
ready
jQuery core .each, $(this) x 2
elems.each(function(i, elem) {
  $(this); // Really inefficient code, you know,
  $(this); // like you see all over the web...
});
ready
jQuery core .each, $(this) x 4
elems.each(function(i, elem) {
  $(this); // Really inefficient code, you know,
  $(this); // like you see all over the web...
  $(this); // Etc...
  $(this); // Etc...
});
ready
jQuery core .each, $(this) x 10
elems.each(function(i, elem) {
  for (var i = 0; i < 10; i++) {
    $(this); // Let's see the cost of doing $(this) 10x.
  }
});
ready
Putting things into perspective...
elems.each2(function(i, jq) {
  // This should give some sense of how disproportionate the
  // $(this) savings are compared to actual DOM manipulations.
  jq.addClass('foo');
});
ready
raw for-loop... with elems.eq(i)
for (var i = 0, len = elems.length; i < len; i++) {
  elems.eq(i); // same as `jq` from each2 base test
}
ready
raw for-loop... with $(elems[i])
for (var i = 0, len = elems.length; i < len; i++) {
  $(elems[i]); // same as `jq` from each2 base test
}
ready
raw for-loop... with $()[..] replacement
// inspired by the each2 plugin itself
var jq = $([1]); // dummy jquery object to use
// admittedly much uglier raw for-loop... but fast
for (var i = 0, len = elems.length; i < len; i++) {
  jq.context = jq[0] = elems[i]; // same as `jq` from each2 base test
}
ready

Revisions

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