Why $.each() is slower than for loop in jquery?

半城伤御伤魂 提交于 2019-12-23 03:37:12

问题


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

Is this because of callback function of $.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 ?

Thanks in Advance.


回答1:


This code comes from within the jQuery.each method:

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

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.

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.

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.

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



来源:https://stackoverflow.com/questions/23969702/why-each-is-slower-than-for-loop-in-jquery

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