【发布时间】:2015-06-26 12:35:20
【问题描述】:
在我正在构建的 Angular 应用程序中,我有两段代码在每次刷新时触发。它们都做同样的事情,但更快的是数组 forEach 函数,我认为它应该稍微慢。
如果您发现错误,那太好了!但是为什么 foreach 循环会快得多。它们紧随其后,如果我改变顺序,也没有什么不同。
第一个更快。使用performance.now() 时平均大约需要 5 毫秒。
var start = performance.now();
start = performance.now();
$scope.config.formTables.forEach(function (e, i, a) {
['tbody', 'thead', 'tfoot'].forEach(function (f, j) {
if (!$scope.config[e][f]) return;
$scope.config[e][f].forEach(function (g, k) {
if(isFunction(g.calculated || {})) g.calculated.apply(g);
})
})
});
console.log(performance.now() - start);
现在是较慢的,我认为应该更快。这需要 100-200 毫秒。
start = performance.now();
var i,j,k,e,f,g;
for(i = 0; i < $scope.config.formTables.length; i++){
e = $scope.config[$scope.config.formTables[i]];
if(e.thead)
for(j = 0; j < e.thead.length; j++){
f = e.thead;
for(k = 0; k < f.length; k++){
//g = f[j];
if(isFunction(f[j].calculated || {})) f[j].calculated.apply(f[j]);
}
}
if(e.tfoot)
for(j = 0; j < e.tfoot.length; j++){
f = e.tfoot;
for(k = 0; k < f.length; k++){
//g = f[j];
if(isFunction(f[j].calculated || {})) f[j].calculated.apply(f[j]);
}
}
if(e.tbody)
for(j = 0; j < e.tbody.length; j++){
f = e.tbody;
for(k = 0; k < f.length; k++){
//g = f[j];
if(isFunction(f[j].calculated || {})) f[j].calculated.apply(f[j]);
}
}
}
console.log(performance.now() - start);
【问题讨论】:
-
请使用更具描述性的变量名,这段代码很难阅读。 (当我试图找出
config[e][f]是否与e.tfoot[j]相同时,我停了下来。) -
jsperf 可用时
-
您的两个代码示例看起来不像在做同样的事情。也许他们是,但它隐藏在我们看不到的数据背后。
标签: javascript angularjs performance for-loop foreach