neuDev33
neuDev33

Reputation: 1623

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?

Upvotes: 1

Views: 5048

Answers (2)

Toporjinschi Sergiu
Toporjinschi Sergiu

Reputation: 1

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

Upvotes: 0

Guffa
Guffa

Reputation: 700382

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.

Upvotes: 4

Related Questions