Does jQuery do any kind of caching of "selectors"?
For example, will the first piece of code perform a full search twice, or is it smart enough to cache results if no DOM changes have occurred?
if ($("#navbar .heading").text() > "") {
$("#navbar .heading").hide();
}
and
var $heading = $("#navbar .heading");
if ($heading.text() > "") {
$heading.hide();
}
If the selector is more complex I can imagine it's a non-trivial hit.
Always cache your selections!
It is wasteful to constantly call $( selector )
over and over again with the same selector.
Or almost always... You should generally keep a cached copy of the jQuery object in a local variable, unless you expect it to have changed or you only need it once.
var element = $("#someid");
element.click( function() {
// no need to re-select #someid since we cached it
element.hide();
});
jQuery doesn't, but there's the possibility of assigning to variables within your expression and then use re-using those in subsequent expressions. So, cache-ifying your example ...
if ((cached = $("#navbar .heading")).text() > "") {
cached.hide();
}
Downside is it makes the code a bit fuglier and difficult to grok.
It's not so much a matter of 'does it?', but 'can it?', and no, it can't - you may have added additional matching elements to the DOM since the query was last run. This would make the cached result stale, and jQuery would have no (sensible) way to tell other than running the query again.
For example:
$('#someid .someclass').show();
$('#someid').append('<div class="someclass">New!</div>');
$('#someid .someclass').hide();
In this example, the newly added element would not be hidden if there was any caching of the query - it would hide only the elements that were revealed earlier.
I just did a method for solving this problem:
var cache = {};
function $$(s)
{
if (cache.hasOwnProperty(s))
{
return $(cache[s]);
}
var e = $(s);
if(e.length > 0)
{
return $(cache[s] = e);
}
}
And it works like this:
$$('div').each(function(){ ... });
The results are accurate as far as i can tell, basing on this simple check:
console.log($$('#forms .col.r')[0] === $('#forms .col.r')[0]);
NB, it WILL break your MooTools implementation or any other library that uses $$
notation.