Why Is Lodash _.each Faster Than The Native For Loop?
Solution 1:
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 ) {returnfalse;} } );
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.
Solution 2:
According to this https://www.measurethat.net/Benchmarks/Show/3268/0/lodash-foreach-vs-for-i-loop lodash is faster than native classical for, but uses more memory
Post a Comment for "Why Is Lodash _.each Faster Than The Native For Loop?"