Dav*_*ing 3 javascript performance jquery caching css-selectors
我知道jQuery不会缓存元素集合,f.ex调用:
$('.myclass').html('hello');
$('.myclass').html('bye');
Run Code Online (Sandbox Code Playgroud)
将使jQuery两次爬上DOM.
但缓存的DOM节点怎么样?
var elems = document.querySelectorAll('.myclass');
$(elems).html('hello');
$(elems).html('bye');
Run Code Online (Sandbox Code Playgroud)
jQuery会在内部缓存这些内容,还是会像第一个例子一样缓慢?
澄清一下:jQuery 是否会在内部保留对内容的引用elems和缓存,$(elems)以便$()每次都不必应用相同的包装器?
就像是:
cache = {}
constructor = function(collection)
if collection in cache
return cache[collection]
else construct(collection)
Run Code Online (Sandbox Code Playgroud)
Jam*_*ice 10
假设我已正确理解你的问题,那么不,jQuery不会在使用它们的语句之外保留对所选节点的引用:
$('.myclass').html('hello'); //Select all .myclass elements, then change their HTML
$('.myclass').html('bye'); //Select all .myclass elements, then change their HTML again
Run Code Online (Sandbox Code Playgroud)
如果单独维护对这些选定节点的引用,则会更快:
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)
Run Code Online (Sandbox Code Playgroud)
差异不会很大(除非你的DOM非常复杂),但会有所不同:

更新
jQuery会保持对elems的引用并在内部缓存$(elems),所以它不必每次都应用相同的$()包装器吗?
不,它不会.如上所述,对匹配的元素集的引用将不会超出其适用的语句.您可以通过保留对整个jQuery对象的引用来提高代码的性能,而不是每次都再次选择它们,甚至每次都将一组存储的本机DOM节点包装在jQuery对象中.
| 归档时间: |
|
| 查看次数: |
6519 次 |
| 最近记录: |