从缓存的选择器中遍历DOM是否比在DOM中查找ID元素要快? [英] Is it faster to traverse the DOM from a cached selector than to find an ID'd element in the DOM?
问题描述
关于通过class或id或其他选择器来查找元素是否更快,存在很多问题.我对此不感兴趣.我想知道你是否有:
There are a lot of questions about whether or not finding an element is faster via class or id or some other selector. I'm not interested in that. I want to know if you have:
var link = $(this); //let's say you're in a click handler
通过查找
var container = link.closest('.container'); //assume container is .container
或
var container = $('#mycontainer'); //assume same element as above
我不仅在上面的特定场景中问这个问题(好吧,是的,在这个场景中也是这样),而是在缓存遍历和创建具有ID的新jQuery对象时问这个问题.我在很多代码中都注意到我倾向于采用前一种方法(因为它可以使自己更具动态性),但是我总是好奇,如果采用后一种方法则更快.
I'm asking this question not just for the particular scenario above (ok, well, yes, for this scenario too) but for cached traversal vs. creating a fresh jQuery object that has an ID. I notice in a lot of my code I tend to do the former method (since it can lend itself to being more dynamic), but I was always curious if it was faster to do it the latter way.
谢谢
推荐答案
我认为,无论是否缓存选择器,使用id选择器都会更快. ID选择器几乎是直接字典查找与缓存/最近的组合的比较,就像字典查找,然后遍历树一样.
I would think that, cached selector or not, it would be faster to use the id selector. The ID selector is pretty much a direct dictionary lookup vs the cached/closest combination which is like a dictionary lookup, followed by a tree traversal.
http://jsperf.com/traverse-from-cached-选择器-vs-id-选择器
最快的查找将通过本机documentGetElementById函数完成.
The fastest lookup would be done with the native documentGetElementById function.
var container = $(document.getElementById('MyContainer'));
这篇关于从缓存的选择器中遍历DOM是否比在DOM中查找ID元素要快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!