Reputation: 10667
var $this = $(this);
Given the above, which is faster: $(".elt", $this)
or $this.find(".elt")
?
I ask because the first seems a bit more concise, but if it converts to $($this).find(".elt")
[sic], it seems that it could in fact be slower.
Upvotes: 1
Views: 504
Reputation: 185963
The performance difference between those two is negligible.
$( 'selector', context )
is transformed into $( context ).find( 'selector' )
at the very beginning of the jQuery $()
function. We are talking microseconds here (if not nanoseconds).
(I prefer the shorter form because it's... well, shorter.)
Upvotes: 3
Reputation: 95047
It is much faster to use $("#elt")
since there is only one element with an id="elt"
that is a valid element. (ID's MUST BE UNIQUE)
Edit: If you were only using that as an example, and the same question applies to using a class instead of an ID, Both ways should be relatively the same due to the way jquery works internally.
$(".elt", $this)
converts to $this.find(".elt")
which is identical to $this.find(".elt")
.
You may find a difference between the two after running several thousand iterations of it at once, but in normal circumstances, you are better off using the one that is easier to read.
Upvotes: 5