简体   繁体   中英

Why is lodash _.each faster than the native for loop?

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.

根据此https://www.measurethat.net/Benchmarks/Show/3268/0/lodash-foreach-vs-for-i-loop lodash 比原生经典 for 快,但使用更多内存

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM