jQuery选择器性能

4 performance jquery children css-selectors

我知道我只是在OCD上花了几毫秒的性能时间,但我只是想知道为什么以下对我来说是真的.这似乎违背了我的逻辑.

我目前有一个div,它在悬停时淡化了里面的图像:

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

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

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

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

有什么想法吗?

Bli*_*ixt 12

之间的区别$(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! -->
Run Code Online (Sandbox Code Playgroud)

$(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! -->
Run Code Online (Sandbox Code Playgroud)

如您所见,使用时不会检查三个元素children,从而提高性能.

  • 好吧,在使用jQuery时计算函数调用的数量是没有意义的,因为在内部,它在处理选择器时调用数十到数百个函数. (2认同)