2012-07-28 99 views
21

我希望$('#childDiv2 .txtClass')$('#childDiv2 input.txtClass')在选择<input type="text" id="txtID" class="txtClass"/>元素时表现更好。但是根据这个performance analysis$('.txtClass');是最好的选择之一。我正在使用JQuery 1.7.2 有没有人对此有过解释?Jquery元素+类选择器性能

Performance analysis for class selectors

HTML

<div class="childDiv2"> 
    <input type="text" id="txtID" class="txtClass"/> 
    <p class="child">Blah Blah Blah</p> 
</div>​ 

JS

$('.txtClass'); 
$('#childDiv2 .txtClass') 
$('#childDiv2 > .txtClass') 
$('input.txtClass') 
$('#childDiv2 input.txtClass') 
+0

由于id必须是唯一的,所以最快的方法是'$(“#txtID”)' – Andreas 2012-07-28 06:56:26

+0

我的关注点是按类选择场景? – Lanka 2012-07-28 07:03:49

+0

伟大的问题。我没有答案,但很奇怪,即使给出上下文$('。txtClass','#childDiv2')仍然比类选择器慢。 – 2012-07-28 07:16:51

回答

36

现代浏览器暴露的非常有效的方法getElementsByClassName()返回具有给定类的元素。这就是为什么一个类选择器在你的情况下更快。

为了详细说明你的例子:

$(".txtClass")     => getElementsByClassName() 

$("#childDiv2 .txtClass")  => getElementById(), 
            then getElementsByClassName() 

$("#childDiv2 > .txtClass")  => getElementById(), 
            then iterate over children and check class 

$("input.txtClass")    => getElementsByTagName(), 
            then iterate over results and check class 

$("#childDiv2 input.txtClass") => getElementById(), 
            then getElementsByTagName(), 
            then iterate over results and check class 

正如你所看到的,这是很合乎逻辑的第一种形式是最快的现代浏览器。

+0

所以我可以告诉的是几乎在网上找到的每个jQuery性能教程都是不正确的。即使是一些jquery人的教程,如[Addy Osmani](http://addyosmani.com/jqprovenperformance/) – Lanka 2012-07-28 07:41:57

+3

@Lanka,也许不是*不正确*,只是*过时*。技术进步,今天最好的绩效建议可能会在明年出错。基准,另一方面,会给你最新的数字。 – 2012-07-28 07:46:34

+0

是的,这是正确的。其实我以前的评论是错误的。那家伙已经在幻灯片中解释了它。 – Lanka 2012-07-28 07:56:37

5

CSS选择器从右向左被解析。所以你的例子

$('#childDiv2 .txtClass') 

将采取两项行动来完成。首先找到类txtClass的所有元素。然后检查每个元素是否为childDiv2的元素的子元素。

$('.txtClass') 

这个选择器只需要一个动作。找到类txtClass

所有元素都在css-tricks.com看看this article

+0

据我所知,嘶嘶声优化此查询。所以它的工作方式与你的解释不同。它首先选择childDiv2,然后在其子节点中搜索txtClass。 – Lanka 2012-07-28 15:35:03

+0

实际上,显示的第一个代码行需要检查每个.txtClass元素以查看它是否是#childDiv2的DESCENDANT。这需要检查每个.txtClass的所有祖先。 – ToolmakerSteve 2014-08-14 05:49:19

1

看起来它也取决于与该类型的元素中的类的元件的密度。

我使用JQuery 1.10.1运行Google Chrome 30.0.1599.69版的测试。随意尝试在另一个浏览器和/或使用另一个JQuery版本。

我试图运行以下测试:

  1. 稀疏(div的10%有类)link to the test on jsbin

  2. 密集(90%div的有类)link to the test on jsbin

貌似在密集的情况下div.class胜,但在稀疏案例.class胜。

+0

像提到密集/稀疏的评论一样,这经常被忽视。如果可以的话,除了使用身份证之外,没有银弹。 – 2015-12-15 10:35:13