在jQuery中查找元素的最有效方法 [英] Most efficient way to find elements in jQuery
问题描述
如果我有一个CSS类,仅 曾经应用于表单元素,例如:
If I have a CSS class which I only ever apply to form elements, eg:
<form class="myForm">
这两个jQuery选择器中哪个效率最高,为什么?
Which of these two jQuery selectors is most efficient, and why?
a) $('form.myForm')
b) $('.myForm')
推荐答案
正如redsquare所述,选择算法在jQuery的更高版本中进行了更改(部分归因于对getElementsByClassName的支持).另外,我使用最新的jQuery版本(v1.6)对此进行了测试,还添加了一个对document.getElementsByClassName的测试以进行比较(至少在Firefox 4和Chrome中有效).
As redsquare already mentioned, the selection algorithm changed in later jQuery versions (partly due to getElementsByClassName support). Additionally, I tested this with the most recent jQuery version to date (v1.6) and also added a test for document.getElementsByClassName for comparison (works at least in Firefox 4 and Chrome).
Firefox 4的结果是:
The results in Firefox 4 were:
// With 100 non-form elements:
$('.myForm') : 366ms
$('form.myForm') : 766ms
document.getElementsByClassName('myForm') : 11ms
// Without any other elements:
$('.myForm') : 365ms
$('form.myForm') : 583ms
document.getElementsByClassName('myForm') : 11ms
可接受的答案已经过时了(仍然可以通过搜索诸如在jquery中找到元素的有效方法"来找到)并且会误导人们,所以我觉得我必须写这个.
The accepted answer is outdated (and is still found by searching for something like "efficient way to find elements in jquery") and can mislead people, so I felt that I have to write this.
另外,请看一下jQuery和本机浏览器选择器功能之间的时差.在jQuery 1.2.6中,$('.myForm')
比getElementsByClassName
慢了 300 倍,而在jQuery 1.6中,它仅 约 20 倍比$('form.myForm')
慢,但仍然快(与过时的答案相反).
Also, take a look at the time difference between jQuery and native browser selector functions. In jQuery 1.2.6 $('.myForm')
was more than 300 times slower than getElementsByClassName
, while in jQuery 1.6 it was only about 20 times slower, but still faster than $('form.myForm')
(contrary to the outdated answer).
注意:结果是使用Firefox 4获得的(与Chrome相似).在Opera 10中,使用标签名称进行查询的速度稍快一些,但Opera还支持速度更快的本机getElementsByClassName
.
Note: The results were obtained with Firefox 4 (similar results with Chrome). In Opera 10 querying with tag name is only slightly faster, but Opera also supports the much faster native getElementsByClassName
.
测试代码: http://jsbin.com/ijeku5
这篇关于在jQuery中查找元素的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!