为什么$ .each()比jquery中的for循环慢? [英] Why $.each() is slower than for loop in jquery?

查看:657
本文介绍了为什么$ .each()比jquery中的for循环慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些来源请求在jquery中优先使用for循环$ .each(),因为 $。each()比for循环 ops / sec

Some sources ask to prefer "for loop over $.each()" in jquery since $.each() is slower than for loop in ops/sec

这是因为的回调函数 $。each()?

任何人都可以解释为什么$ .each

Can anybody explain Why $.each() is slower than for loop in jquery and In which case i have to choose for loop over $.each() or vice verse ?

感谢在前进。

推荐答案

此代码来自 jQuery.each 方法:

for ( ; i < length; i++ ) {
    value = callback.call( obj[ i ], i, obj[ i ] );
    if ( value === false ) {
        break;
    }
}

code> jQuery.each 函数是 for 循环。这是完全不可避免的,它应该是更慢,特别是使用 Function#call

So inside the jQuery.each function is a for loop. It is completely inevitable that it should be slower, especially given that it uses Function#call.

for 循环将更快。但是仍然有用例的jQuery方法。首先,因为它很少显着地较慢。如果您有性能关键代码,请使用 for 循环。但很常见的是,在本地代码和jQuery代码之间将存在零可辨别的差异。根据你给出的jsPerf链接, for 循环的速度提高了大约30倍。但是在我的(不是很强大的)系统上,它的第二个 0.0015 0.000052 循环中的代码将更加显着;你可能不会注意到差异。

So yes, the for loop will be faster. But there are still use-cases for the jQuery method. First, because it is very rarely significantly slower. If you have performance-critical code, use the for loop. But very frequently there will be zero discernable difference between the native code and the jQuery code. According to the jsPerf link you give, the for loop is about 30 times faster. But on my (not very powerful) system it's the difference between 0.0015 of a second and 0.000052 of a second. The code within the loop will be far more significant; you probably won't notice the difference.

其次,jQuery方法(像原生的 Array.forEach )使用循环的每次迭代的函数,所以它改变范围,而 for 循环不会。这通常是所希望的。当你需要一个闭包或者你想限制一个变量到你的代码的一小部分。

Second, the jQuery method (like the native Array.forEach method) uses functions for each iteration of the loop, so it changes the scope, whereas for loops do not. This is frequently desirable, e.g. when you need a closure or when you want to limit a variable to a small section of your code.

所以基本上你应该使用 code>循环,当性能真的重要,并使用jQuery的等效,当它使你的生活更轻松。

So basically you should use for loops when performance really matters and use jQuery's equivalents when it makes your life easier.

这篇关于为什么$ .each()比jquery中的for循环慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆