Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery cache elements internally?

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)
like image 573
David Hellsing Avatar asked Dec 15 '22 19:12

David Hellsing


1 Answers

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:

$('.myclass').html('hello'); //Select all .myclass elements, then change their HTML
$('.myclass').html('bye'); //Select all .myclass elements, then change their HTML again

If you maintain a reference to those selected nodes separately, it will be faster:

var elems = document.querySelectorAll('.myclass'); //Select all .myclass elements
$(elems).html('hello'); //Change their HTML (no need to select them)
$(elems).html('bye'); //Change their HTML (no need to select them)

The difference won't be massive (unless your DOM is very complicated) but there will be a difference:

enter image description here


Update

will jQuery keep a reference to elems and cache $(elems) internally so it won’t have to apply the same $() wrapper every time?

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.

like image 187
James Allardice Avatar answered Dec 18 '22 09:12

James Allardice