我知道,我只是强迫症有关的价值表演时间为几毫秒,但我只是想知道为什么下面是我真实的。 这似乎违背了我的逻辑。
我目前有一个具有内淡出图像上悬停一个div:
$('div.someclass').hover(function() {
$(this).children('img').fadeOut(function(){
// do something
});
}, function() {
// do something
});
一些测试后,(通过选择器1000循环次,取的9次试验的平均值)我已经使用3个不同的选择器,并得出结论,该速度是在该顺序:
-
$(this).children('img')
中运行速度最快的-avg约400ms的; -
$('img', this)
-平均大约900毫秒; 和 -
$(this).find('img')
运行最慢的-平均约1000毫秒
这违背了具有两个函数调用会比一个慢的逻辑。 另外,我已阅读,在内部,jQuery的第二种情况第三种情况进行转换,以便将第三种情况是比较慢?
有什么想法吗?
之间的差异$(this).find('img')
和$(this).children('img')
是, children
函数只查找直接 <img>
的后裔,而find
功能发现任何<img>
元素在下面的DOM层次结构的任何地方$(this)
。 这就是为什么children
更快。
$(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
,从而提高性能。