jQuery 选择器性能

2024-03-11

我知道我只是对几毫秒的表演时间有强迫症,但我只是想知道为什么以下内容对我来说是正确的。这似乎违背了我的逻辑。

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

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

经过一些测试,(循环选择器 1000 次,取 9 次测试的平均值)我使用了 3 个不同的选择器,得出的结论是速度按以下顺序排列:

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

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

有什么想法吗?


和...之间的不同$(this).find('img') and $(this).children('img')那是children函数只寻找direct <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,从而提高性能。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jQuery 选择器性能 的相关文章