为什么lodash _each比native for loop更快? [英] Why is lodash _.each faster than the native for loop?
问题描述
其中_.each比原生for循环快。
有人可以帮我理解为什么吗?或者指出我的例子有什么问题?
当我尝试这段代码时,jsbin会在中间停止代码,因为它认为存在一个无限循环。添加到顶部关闭此功能:
// noprotect;
lodash循环实际上不会退出您想要的位置。您必须返回 false
来停止循环:
_。each (array,function(a){if(a === 50000){return false;}});
有了这些修复程序,当我运行代码时,我看不到任何一致的性能差异。有时候,第一个循环稍微快一点,有时候第二个。测试运行之间的时间差异大于两个循环之间的差异。
lodash代码运行得非常快,考虑到有一个函数调用,但JavaScript编译器可能实际上消除(我在Firefox中测试)。
更新:
测试的大部分时间似乎是开销。当我把数组放大十倍,而出口点的一半时,第一个循环的时间只有三倍,而第二个循环的时间只有两倍。现在,本地循环几乎是lodash循环的两倍。
即使本机循环快两倍,这也不是什么大的差别。通常你在循环中做的工作比循环要花费更多的时间,所以大多数情况下你应该使用最方便的循环形式。
JSPerf says the native for loop is the fastest of all similar loop implementations. However, I tried a simple example here -https://jsbin.com/kivesopeqi/edit?html,js,output where _.each is way faster than the native for loop.
Can someone help me understand why? Or point out something wrong with my example?
First you have to have to make sure that you don't compare apples and oranges.
When I try the code, jsbin will stop the code in the middle because it thinks that there is an infinite loop. Add this to the top to turn this feature off:
"//noprotect";
The lodash loop doesn't actually exit where you want it to. You have to return false
to stop the loop:
_.each( array, function( a ) { if( a === 50000 ) {return false;} } );
With those fixes, when I run the code I don't see any consistent performance difference. Sometimes the first loop is slightly faster, sometimes the second. The times between test runs varies more than the difference between the two loops.
The lodash code runs surprisingly fast considering that there is a function call, but the JavaScript compiler might actually do away with that (I'm testing in Firefox).
Update:
Most of the time for the test seems to be overhead. When I make the array ten times bigger, and the exit points half of that, the time for the first loop only about triples and the time for the second loop only doubles. Now the native loop is almost twice as fast as the lodash loop.
Even if native loops are twice as fast, that is not a big difference. Normally the work that you do in a loop takes a lot more time than the loop itself, so most of the time you should use the loop form that is most convenient for what you are doing.
这篇关于为什么lodash _each比native for loop更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!