jQuery selectors performance

那年仲夏 提交于 2020-01-13 11:44:11

问题


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.

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
});

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:

  1. $(this).children('img') runs the fastest -avg about 400ms;
  2. $('img', this) - avg about 900ms; and
  3. $(this).find('img') runs the slowest - avg about 1000ms

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?.

Any thoughts?


回答1:


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! -->

As you can see, there are three elements that won't be checked when using children, thus increasing performance.



来源:https://stackoverflow.com/questions/1186696/jquery-selectors-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!