I've been using $.each to do iterations for a while now, but I keep on hearing people say to use native JS for to do loops. I'm very concerned about performance but I am not sure if it's always possible to replace $.each with for in a meaningful way.
So my questions are, is it possible to always replace $.each with for, and if not what's the rule of thumb for when it can be done and when it cannot.
I have an each like this:
$this.find("div.class").each(function (){
var $thisparent = $(this).parent();
if (condition) {
$(this).prepend($thisparent.text());
}
if (condition2) {
$(this).prepend($thisparent.text());
}
});
This is what jQuery does with .each
, basically:
$.fn.each = function(callback) {
var i, length = this.length;
for(i = 0; i < length; ++i) {
callback.call(this[i]);
}
};
So it's not hard to substitute your anonymous function's 'contents' with the callback.call
call. Just be sure to replace this
with a temporary with the jQuery object.
Converting your supplied code:
var foo = $this.find("div.class"),
fooLength = foo.length,
i,
$thisparent;
for (i = 0; i < fooLength; ++i) {
$thisparent = $(foo[i]).parent();
if (condition) {
$(foo[i]).prepend($thisparent.text());
}
if (condition2) {
$(foo[i]).prepend($thisparent.text());
}
}
For additional (potential) speed, cache foo[i]
into a temporary. too, and assign $thisparent
only when needed. If condition
and condition2
are mutually exclusive, use a single if (condition || condition2)
.
Someone compared the performance of for
and $.each
:
http://jquery-howto.blogspot.com/2009/06/javascript-for-loop-vs-jquery-each.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With