jQuery按类选择VS按属性选择 [英] jQuery select by class VS select by attribute
问题描述
我只想问一个关于性能的意见: 使用jquery按类名或按属性名选择元素更快吗? 示例我有100个DIVs元素以这种形式出现:
I want just to ask for an opinion of perfomance: Is it faster selecting elements by class name or by attribute name with jquery? Example I have 100 DIVs element in this form:
<div class="normal_box" normal_box=1>...</div>
哪个更快?
$('div.normal_box').each(function(){...});
VS
$('div[normal_box=1]').each(function(){...});
我在30个div上进行了一些实验,但与(new Date).getTime();没什么区别. 也许按类别选择会更有效地利用CPU?
I made some experiments on 30 divs but I don't see any difference with (new Date).getTime(); Maybe selecting by class is more efficient on CPU usage?
推荐答案
这是一篇关于您正在寻找的好帖子.
this is a great post for exactly what you are looking for.
我也找到了一篇很棒的文章,可能会对您有帮助:
I've also found a great article that may help you on this topic:
谢谢,谢谢.
更新:我已经设法制作了一个样本来匹配您发布的案例,这是总共203个div的结果:
update: I've managed to make a sample to match your posted case, here are the results for a total set of 203 divs:
1-通过使用具有证书类名称$("div.normal_box")
==> 884 ms
1- by using tag name having certine class name $("div.normal_box")
==> 884 ms
2-通过使用属性值$("div[normal_box=1]")
==> 4553毫秒
2- by using attribute value $("div[normal_box=1]")
==> 4553 ms
更新2: 我尝试了比您的问题更多的尝试,并测试了一些选择器,这是此更新测试的新链接:
Update 2: I tried even further more than your question, and made it to test a few selectors, here is the new link for this updated test: http://jsfiddle.net/8Knxk/4/
3-通过使用标签名称$("div")
==> 666毫秒
3- by using tag name $("div")
==> 666 ms
4-仅使用类名称$(".normal_box")
==> 762 ms
4- by using just the class name $(".normal_box")
==> 762 ms
我认为现在对您来说更清楚了:)
I think it's now more clear for you :)
这篇关于jQuery按类选择VS按属性选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!