Does jQuery cache elements internally?

2019-05-11 16:13发布

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)

2条回答
放荡不羁爱自由
2楼-- · 2019-05-11 16:34

If "cache" means "keep the DOM elements in the internal collection for that jQuery object" .. then yes.

Imagine

jq = $(elementListOrSelector)

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.

查看更多
唯我独甜
3楼-- · 2019-05-11 16:48

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.

查看更多
登录 后发表回答