$('.class').doSomehting();
$('.class').doSomethingElse();
$('.class').thirdThing();
in favor of var ele = $('.class');
ele.doSomething();
ele.doSomethingElse();
ele.thirdThing();
I would only assume that re-querying with the jQuery object inside of event handlers has the same adverse effects.Lets say you have a very simple tabbed thing
//this is code that i've seen around
var tabs = $('a.tab'),
containers = $('div.container');
tabs.click(function(e){
var index = tabs.indexOf($(this));
tabs.removeClass('active');
$(this).addClass('active');
containers.css('display', 'none');
$(containers[index]).css('display', 'block');
});
vs
//this is how id handle a simple tabber
var tabs = $('a.tab'),
containers = $('div.container'),
all_containers = $.map(containers, function(i, c){
return $(c);
}); $.each(all_tabs, function(i, tab){
var t = $(tab);
t.bind('click', function(e){
tabs.removeClass('active');
t.addClass('active');
containers.css('display', 'none');
all_containers[i].css('display', 'block');
});
});
I just feel that the first one, while more concise (has it obvious areas of improvement, but general idea) would wind up being more expensive than the second.If running the jQuery object isnt too expensive, why is the practice of rerunning the same selector frowned upon?