我正在尝试查找具有以下内容的元素:
doc.querySelectorAll('#divContentList article');
它运行良好,但另一位开发人员告诉我我应该写:
doc.querySelector('#divContentList').querySelectorAll('article');
他说这样更好,因为它直接转到 #divContentList
,然后查找 article
元素。
我不认为他的解决方案在速度性能上是最好的,并且它搜索元素两次。
我认为 querySelectorAll
足以完成其工作。
主要问题是,哪一行代码整体上最好?
最佳答案
感谢Mauricio Soares与他的 jsPerf 第一个示例:
<div id="divContentList">
<article></article>
</div>
确实是第一种方法:
doc.querySelectorAll('#divContentList 文章');
如果其中只有一篇文章
,速度会更快。
我将 jsPerf 从 10 条修改到 1000 条文章
,性能差异非常显着。 Check it here
<div id="divContentList">
<article></article>
...
<article></article>
</div>
这将导致我的问题的第二种方法:
doc.querySelector('#divContentList').querySelectorAll('article');
快得多
最后,使用 getElementById
的性能会略有提高。
doc.getElementById('divContentList').querySelectorAll('article');
那是最好的表现
Keith Rousseau querySelectorAll
从右到左计算,这是正确的。
编辑:
此外,我还发现了 querySelector
和 getElementById/getElementsByTagName
的一些不同之处。 querySelector 返回静态 NodeList,而 getElementById 返回 Live NodeList。
我又做了一个test
document.getElementById('divContentList').getElementsByTagName('article');
这一个占据了蛋糕。差别很可笑
关于javascript - doc.querySelectorAll ('#id element' ) 与 doc.querySelector ('#id' ).querySelectorAll ('element' ) 之间的性能;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28432763/