jQuery 选择器性能
我知道我只是对几毫秒的表演时间有强迫症,但我只是想知道为什么以下内容对我来说是正确的。 这似乎违背了我的逻辑。
我目前有一个 div,它在悬停时淡出内部图像:
$('div.someclass').hover(function() {
$(this).children('img').fadeOut(function(){
// do something
});
}, function() {
// do something
});
经过一些测试(循环选择器 1000 次,取 9 次测试的平均值)我使用了 3 个不同的选择器,得出的结论是速度按以下顺序排列:
- < code>$(this).children('img') 运行最快 -avg 约 400ms;
$('img', this)
- 平均约 900ms; 而$(this).find('img')
运行速度最慢 - 平均约 1000ms
这违背了两个函数调用比一个函数调用慢的逻辑。 另外,我在内部读到,jQuery 将第二种情况转换为第三种情况,那么第三种情况会更慢吗?
有什么想法吗?
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:
$(this).children('img')
runs the fastest -avg about 400ms;$('img', this)
- avg about 900ms; and$(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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
$(this).find('img')
和$(this).children('img')
之间的区别在于children
函数仅查找直接后代,而
find
函数则查找任何DOM 层次结构中
$(this)
以下任意位置的元素。 这就是为什么children
更快。$(this).children('img')
:$(this).find('img')
:正如你所看到的,有三个元素会'使用
children
时不进行检查,从而提高性能。The difference between
$(this).find('img')
and$(this).children('img')
is that thechildren
function only looks for direct<img>
descendants, while thefind
function finds any<img>
element anywhere in the DOM hierarchy below$(this)
. That's whychildren
is faster.$(this).children('img')
:$(this).find('img')
:As you can see, there are three elements that won't be checked when using
children
, thus increasing performance.