为什么lodash.each比原生forEach更快? [英] Why is lodash.each faster than native forEach?
问题描述
我试图找到运行具有自己范围的for循环的最快方法。我比较的三种方法是:
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]);
}
这是在OS X上的Chrome 29上。您可以在这里自行运行测试:
This is on Chrome 29 on OS X. You can run the tests yourself here:
lodash的 .each
几乎是本机 .forEach的两倍
?而且,它如何比的普通更快?巫术?黑魔法?
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?
推荐答案
_。each()
不完全兼容到 []。forEach()
。请参阅以下示例:
_.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
所以lodash的实施缺少 if(... in ...)
check,这可能解释了性能差异。
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
这篇关于为什么lodash.each比原生forEach更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!