jQuery是否在内部缓存元素?

我知道jQuery不会缓存元素集合,f.ex调用:

$('.myclass').html('hello'); $('.myclass').html('bye'); 

将使jQuery两次爬上DOM。

但缓存的DOM节点怎么样?

 var elems = document.querySelectorAll('.myclass'); $(elems).html('hello'); $(elems).html('bye'); 

jQuery会在内部缓存这些内容,还是会像第一个例子一样缓慢?

澄清一下:jQuery是否会在内部保留对elems的引用并缓存$(elems)以便每次都不必应用相同的$()包装器?

就像是:

 cache = {} constructor = function(collection) if collection in cache return cache[collection] else construct(collection) 

假设我已正确理解你的问题,那么不,jQuery不会在使用它们的语句之外保留对所选节点的引用:

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

如果单独维护对这些选定节点的引用,则会更快:

 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) 

差异不会很大(除非你的DOM非常复杂),但会有所不同 :

在此处输入图像描述


更新

将jQuery保持对elems的引用并在内部缓存$(elems),以便每次都不必应用相同的$()包装器吗?

不,它不会。 如上所述,对匹配的元素集的引用将不会超出其适用的语句。 您可以通过保留对整个jQuery对象的引用来提高代码的性能,而不是每次都再次选择它们,甚至每次都将一组存储的本机DOM节点包装在jQuery对象中。

如果“缓存”意味着“将DOM元素保留在该jQuery对象的内部集合中”,那么是的。

想像

 jq = $(elementListOrSelector) 

其中jq[0..jq.length-1]分别评估DOM元素。 例如, jq[0]计算为jQuery对象表示的第一个DOM元素(如果有)。 请注意,一旦构建了这个集合,它就不会被神奇地改变 (并且它的构建方式无关紧要)。

但是,除了保留特定 jQuery对象的直接结果之外,没有“缓存”。