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:
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?
lambda
thing for? Why don't you simply putcb
directly?.each()
is much slower than any other method in your test, for me.FF 23.0.1
.each()
andfor
comes from the additional function lookup (lambda
). See jsperf.com/lo-dash-each-vs-native-foreach/15 for a more meaningful benchmark.