Reputation: 1847
Lately i have been wondering if there is a performance difference between repeating the selector just over and over again or just using a var and store the selector in that and just refer to it.
$('#Element').dothis();
$('#Element').dothat();
$('#Element').find('a').dothat();
or just
var Object = $('#Element');
Object.dothis();
Object.dothat();
$('a', Object).dothat();
I prefer the second way because it looks cleaner and is better maintainable.
Upvotes: 8
Views: 1864
Reputation:
Storing the results from you jQuery selection to a variable is faster. This is because jQuery dosen't need to lookup the results every time you try to access them.
I put together some performance metrics: http://jsperf.com/jquery-selectors-vs-stored-variable
On Chrome 26.0.1410.63 on Mac OS X 10.8.2:
Selecting: 40,276 ops/sec
Storing the variable: 594,031,358 ops/sec
Upvotes: 1
Reputation: 41433
expending on Ghommey's method
var Object = $('#Element');
Object
.dothis()
.dothat()
.find('a')
.dothat();
Faster, and stores the object for later use.
Upvotes: 2
Reputation: 11366
The second way has a performance benefit. It may or may not be great but it is better. In the first version, you're doing dom traversal 4 times, in the second you only do 2.
Pretty good article on speeding up jQuery here: http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/
Upvotes: 1
Reputation: 38140
There is another fast way. It is as fast as your second code.
$('#Element')
.dothis()
.dothat()
.find('a')
.dothat();
Upvotes: 3
Reputation: 10451
There is certainly a performance difference, since sizzle does not have to be executed each time, however, there is also a functionality difference. If the dom happens to change between the 1st and 3rd calls, the cached jQuery object will still contain the old set of elements. This can often occur if you cache a set and then use it in a callback.
Upvotes: 7
Reputation: 187040
I prefer the second way. It will be easier to maintain code even if an element id or class changes.
Upvotes: 4