Jquery元素+类选择器性能

当我选择元素时,我希望$('#childDiv2 .txtClass')$('#childDiv2 input.txtClass')表现更好。 但是根据这个性能分析 $('.txtClass'); 是其中最好的选择者。 我正在使用JQuery 1.7.2有没有人对此有解释?

类选择器的性能分析

HTML

 

Blah Blah Blah

JS

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

现代浏览器公开了一个非常有效的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 

正如您所看到的,第一种forms在现代浏览器上最快是合乎逻辑的。

 var obj = document.getElementById("childDiv"); xxx = obj.getElementsByClassName("txtClass"); 

快了30倍。

http://jsperf.com/selectors-perf/6

CSS选择器从右到左进行解析。 所以你的榜样

 $('#childDiv2 .txtClass') 

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

 $('.txtClass') 

这个选择器只需一个动作。 使用类txtClass查找所有元素

在css-tricks.com上查看这篇文章

看起来它还取决于类型元素中具有类的元素的密度。

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

我试着运行以下测试:

  1. 稀疏(10%的div有类) 链接到jsbin上的测试

  2. 密集(90%的div有类) 链接到jsbin上的测试

Dense案例中看起来像div.class获胜,但在Sparse案例中 .class获胜。