jQuery选择器性能

4

我知道我对几毫秒的性能时间过于追求完美,但我只是想知道为什么以下内容对我来说是真实的。它似乎与我的逻辑相悖。

我目前有一个div,在悬停时将图像淡出:

$('div.someclass').hover(function() {
    $(this).children('img').fadeOut(function(){
        // do something
    });
}, function() {
    // do something
});

经过一些测试(循环选择器1000次,取9个测试的平均值),我使用了3个不同的选择器,并得出速度如下:

  1. $(this).children('img')运行最快-平均约为400毫秒;
  2. $('img', this) - 平均约为900毫秒;和
  3. $(this).find('img')运行最慢-平均约为1000毫秒

这与有两个函数调用比一个更慢的逻辑相反。此外,我读到jQuery在内部将第二种情况转换为第三种情况,那么第三种情况会更慢吗?

有什么想法吗?

1个回答

12

$(this).children('img') 只会查找直接的 <img> 子元素,因此比find函数更快。

<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 时,有三个元素不会被检查,从而提高了性能。


还想指出的是,$('img', this) 也不一定是一个函数调用,因为所提到的转换过程也可能调用任意数量的函数。 - Ian Selby
2
在使用jQuery时计算函数调用次数是没有意义的,因为在处理选择器时,它内部会调用数十到数百个函数。 - Blixt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接