javascript - jQuery 是否在内部缓存元素?

标签 javascript jquery performance caching css-selectors

我知道 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 非常复杂)但会有 be a difference :

enter image description here


更新

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

不,不会。如上所述,对匹配元素集的引用将不会在其适用的声明之外保留。您可以通过保留对自始至终使用的 jQuery 对象的引用来提高代码的性能,而不是每次都重新选择它们,甚至每次都将一组存储的 native DOM 节点包装在 jQuery 对象中。

关于javascript - jQuery 是否在内部缓存元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12276787/

相关文章:

Javascript - 更改指定元素中元素的src

javascript - 用于匹配任何语言的 HashTags 的正则表达式

javascript - 如何使用 Jest 单元测试触发 transitionend

javascript - Meteor 应用程序访问其根目录之外的文件

php - 你能有一个设置为数组的 PHP $_POST 变量吗?

javascript - 选择的 AngularJS 性能

r - 解析时间戳需要很长时间

javascript - Fire Event before 'focus' kicks in/Fire Event before keyboard appears on iOS

jquery - ASP.NET 的 jqGrid 的免费替代品?

python - 提高 pandas python 的性能