I was trying to find the fastest way of running a for loop with its own scope. The three methods I compared were:
var a = "t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t".split(); // lodash .each -> 1,294,971 ops/sec lodash.each(a, function(item) { cb(item); }); // native .forEach -> 398,167 ops/sec a.forEach(function(item) { cb(item); }); // native for -> 1,140,382 ops/sec var lambda = function(item) { cb(item); }; for (var ix = 0, len = a.length; ix < len; ix++) { lambda(a[ix]); }
This is on Chrome 29 on OS X. You can run the tests yourself here:
http://jsben.ch/BQhED
How is lodash's .each
almost twice as fast as native .forEach
? And moreover, how is it faster than the plain for
? Sorcery? Black magic?
Deductions. This foreach loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array. The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
One killer feature of lodash is chains / sequences. Chains / sequences are lazy, in contrast with the native Array methods, which are eager. This means that lodash has better performance, because it minimizes the amount of work it does.
As the result of the article in jsperf.com (2015)shows that, Lodash performances faster than Native Javascript.
Lodash is extremely well-optimized as far as modern JS goes, but, as you may know, nothing can be faster than native implementation. Even if Lodash uses the same API under-the-hood, function call overhead is still present.
_.each()
is not fully compatible to [].forEach()
. See the following example:
var a = ['a0']; a[3] = 'a3'; _.each(a, console.log); // runs 4 times a.forEach(console.log); // runs twice -- that's just how [].forEach() is specified
http://jsfiddle.net/BhrT3/
So lodash's implementation is missing an if (... in ...)
check, which might explain the performance difference.
As noted in the comments above, the difference to native for
is mainly caused by the additional function lookup in your test. Use this version to get more accurate results:
for (var ix = 0, len = a.length; ix < len; ix++) { cb(a[ix]); }
http://jsperf.com/lo-dash-each-vs-native-foreach/15
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With