I know jQuery doesn’t cache collections of element, f.ex calling:
$('.myclass').html('hello');
$('.myclass').html('bye');
Will make jQuery climb the DOM twice.
But how about cached DOM nodes?
var elems = document.querySelectorAll('.myclass');
$(elems).html('hello');
$(elems).html('bye');
Will jQuery cache those internally, or will they be equally slow as the first example?
To clarify: will jQuery keep a reference to elems
and cache $(elems)
internally so it won’t have to apply the same $()
wrapper every time?
Something like:
cache = {}
constructor = function(collection)
if collection in cache
return cache[collection]
else construct(collection)
If "cache" means "keep the DOM elements in the internal collection for that jQuery object" .. then yes.
Imagine
where
jq[0..jq.length-1]
evaluate to the respectively DOM element. For instance,jq[0]
evaluates to the first DOM element represented by the jQuery object, if any. Note that this collection is not magically changed once it has been built (and the way in which it was built does not matter).However there is no "cache" outside of simply keeping the immediate results for that particular jQuery object.
Assuming I've understood your question correctly, then no, jQuery won't keep a reference to the selected nodes beyond the statement that uses them:
If you maintain a reference to those selected nodes separately, it will be faster:
The difference won't be massive (unless your DOM is very complicated) but there will be a difference:
Update
No, it won't. As stated above, the reference to the matched set of elements will not be maintained beyond the statement to which it applies. You can improve the performance of your code by keeping a reference to jQuery objects that are used throughout, rather than selecting them again each time, or even wrapping a stored set of native DOM nodes in a jQuery object each time.