Is it recommended that, when I need to access the result of a jQuery selector more than once in the scope of a function, that I run the selector once and assign it to a local variable?
Forgive my trite example here, but i think it illustrates the question.
So, will this code perform faster:
var execute = function(){
var element = $('.myElement');
element.css('color','green');
element.attr('title','My Element');
element.click(function(){
console.log('clicked');
});
}
than this code:
var execute = function(){
$('.myElement').css('color','green');
$('.myElement').attr('title','My Element');
$('.myElement').click(function(){
console.log('clicked');
});
}
If there is no difference, can anyone explain why? Does jQuery cache elements after selecting them so subsequent selectors don’t have to bother searching the dom again?
Reusing the selector reference, your first case, is definitely faster. Here’s a test I made as proof:
http://jsperf.com/caching-jquery-selectors
The latter case, redefining your selectors, is reported as ~35% slower.