var createReduce = function(dir) {
// Wrap code that reassigns argument variables in a separate function than
// the one that accesses `arguments.length` to avoid a perf hit. (#1991)
// 为什么要将函数额外复制给变量,上面提到的perf hit 具体是什么呢?
var reducer = function(obj, iteratee, memo, initial) {
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
index = dir > 0 ? 0 : length - 1;
if (!initial) {
memo = obj[keys ? keys[index] : index];
index += dir;
}
for (; index >= 0 && index < length; index += dir) {
var currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
};
return function(obj, iteratee, memo, context) {
var initial = arguments.length >= 3;
return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
};
};
“perf hit” 是 “performance hit” 的缩写,直译是 “性能打击”,意指能够对系统性能引起问题的东西。代码中的注释是说避免使用 “arguments.length” 以免引起性能问题。这是因为使用 “arguments” 的话将导致 Chrome 和 Node 中使用的 V8 引擎跳过对其的优化,造成性能问题。具体可以看一下这篇文章:http://www.jstips.co/zh_cn/ja... 以及 underscore 关于这个问题的 issue:https://github.com/jashkenas/...