Details:
Commonly-used jQuery selectors should be cached.
var $thing = $("#thing");
// ...lots of invocations of $thing...
It can be handy (and sometimes, arguably more performant) to select an outer div and then use .find()
to get an inner element, especially if you're going to grab multiple things from within that div.
var $outerDiv = $("div#outer");
var $thing1 = $outerDiv.find(".thing1");
var $thing2 = $outerDiv.find(".thing2");
// ...etc....
But what if I have lots of outer divs and never use them after initially finding the necessary children?
var $outerDiv1 = $("div#outer1");
var $foo1 = $outerDiv1.find(".foo1");
var $foo2 = $outerDiv1.find(".foo2");
// ...etc....
var $outerDiv2 = $("div#outer2");
var $bar1 = $outerDiv2.find(".bar1");
var $bar2 = $outerDiv2.find(".bar2");
// ...etc....
Now I have $outerDiv1
, $outerDiv2
, etc. sitting in the global namespace taking up memory.
My questions are:
- Should I be caching jQuery selectors in the global namespace at all? Why (not)?
- If I place cached selectors in some namespace other than global, will the later-unreferenced
$outerDiv*
variables be cleaned up in garbage collecting? - Are the performance costs/benefits negligible anyway for a typical web page?
Note:
My question assumes the truth of the accepted answer for the question "jQuery object: to cache or not to cache?". It's not a duplicate, because it expands by considering the memory impact if we know some of the globally-cached selectors won't ever be used again.