Reputation: 1638
When using jQuery, I know that you should store an object rather than repeatedly transversing the DOM:
// This is good
var something = $(".some-class")
My question is does the jQuery $(this)
have a similar performance issue? Should I be doing this:
// should I do this?
var current_object = $(this)
with $(this)
?
(This is my obligatory this
is confusing joke)
Upvotes: 0
Views: 48
Reputation: 79566
$(this)
isn't free. It instantiates a new jQuery object. But compared to traversing the DOM, it's very nearly free.
This level of optimization is usually unnecessary. Write code that's readable, and optimize this sort of thing only when you experience performance bottlenecks.
My rule, for something like var foo = $(this)
is: Use whatever's easier to read in the situation.
$(this)
has a pretty clear meaning, so use it when it makes sense. But if you're doing something where it makes sense to call $(this)
by another name, do that.
Optimize for you and your fellow coder's time. It's the most valuable resource in the equation.
Upvotes: 1