jQuery选择器性能 [英] jQuery selectors performance
问题描述
我知道我只是OCD大约几毫秒的性能时间,但我只是想知道为什么下面是我的真实。这似乎违背了我的逻辑。
I know I'm just being OCD about a few milliseconds worth of performance time, but I was just wondering why the following is true for me. It seems goes against my logic.
我目前有一个div已经淡出的图像里面悬停:
I currently have a div that has fades out the image inside on hover:
$('div.someclass').hover(function() {
$(this).children('img').fadeOut(function(){
// do something
});
}, function() {
// do something
});
经过一些测试(循环通过选择器1000次,取9次测试的平均值) 3个不同的选择器,并得出结论,速度是按照此顺序:
After some testing, (looping through selectors 1000 times, taking the average of 9 tests) I have used 3 different selectors and concluded that the speed is in this order:
-
$(this).children ')
运行最快的-avg大约400ms; -
$('img',this)
平均约900ms;和 -
$(this).find('img')
运行最慢 - 平均约1000ms
$(this).children('img')
runs the fastest -avg about 400ms;$('img', this)
- avg about 900ms; and$(this).find('img')
runs the slowest - avg about 1000ms
这违背了两个函数调用比一个慢的逻辑。另外,我已经在内部读取,jQuery将第二种情况转换为第三种情况,所以第三种情况会更慢。
This goes against the logic that having two function calls would be slower than one. Plus, I have read that internally, jQuery converts the second case to the third case so would the third case be slower?.
任何想法?
推荐答案
$(this).find('img')
和 $(this).children('img')
是 children
函数只查找 < img>
后代,而 find
函数找到< img& code>元素
$(this)
下的DOM层次结构中的任何位置。这就是为什么 children
更快。
The difference between $(this).find('img')
and $(this).children('img')
is that the children
function only looks for direct <img>
descendants, while the find
function finds any <img>
element anywhere in the DOM hierarchy below $(this)
. That's why children
is faster.
$(this).children('img' )
:
<h1> <!-- Is this img? Nope! -->
<img alt="" src="..." /> <!-- Never checked. -->
<span>Bla bla</span> <!-- Never checked. -->
</h1>
<a href="#"> <!-- Is this img? Nope! -->
<img alt="" src="..." /> <!-- Never checked. -->
</a>
<img alt="" src="..." /> <!-- Is this img? Yeah, return it! -->
$(this).find('img')
:
<h1> <!-- Is this img? Nope! -->
<img alt="" src="..." /> <!-- Is this img? Yeah, return it! -->
<span>Bla bla</span> <!-- Is this img? Nope! -->
</h1>
<a href="#"> <!-- Is this img? Nope! -->
<img alt="" src="..." /> <!-- Is this img? Yeah, return it! -->
</a>
<img alt="" src="..." /> <!-- Is this img? Yeah, return it! -->
正如你所看到的,有三个元素,当使用 children
,从而提高性能。
As you can see, there are three elements that won't be checked when using children
, thus increasing performance.
这篇关于jQuery选择器性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!