jQuery each2 plugin vs jQuery core .each method
JavaScript performance comparison
Info
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!
Again, not sure why .each$ is that much faster than Ben's implementation. I am using a for loop instead of while.
Preparation code
<script src="//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>
Preparation code output
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
jQuery each2 plugin |
|
pending… |
jQuery core .each method |
|
pending… |
jQuery core .each, $(this) x 2 |
|
pending… |
jQuery core .each, $(this) x 4 |
|
pending… |
jQuery core .each, $(this) x 10 |
|
pending… |
Putting things into perspective... |
|
pending… |
jQuery .each$ plugin |
|
pending… |
Putting things into perspective... with .each$ plugin |
|
pending… |
Putting things into perspective... with jQuery core .each |
|
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:
- Revision 1: published by "Cowboy" Ben Alman
- Revision 2: published by "Cowboy" Ben Alman
- Revision 3: published
- Revision 4: published by David
- Revision 5: published by David
- Revision 6: published by Kyle Simpson and last updated
- Revision 7: published by Flatlineato
- Revision 13: published by Scott Rycroft
- Revision 15: published by Scott Rycroft
- Revision 16: published by Jason DiMeo
- Revision 18: published by Jason DiMeo
- Revision 22: published by creage
- Revision 23: published
- Revision 24: published
- Revision 25: published
0 comments