While working on an Angular application, I encountered a curious situation where two pieces of code execute upon every refresh. Surprisingly, the faster one happens to be the array forEach function, which is typically considered slower in performance.
I'm puzzled as to why the foreach loop yields better speed results compared to its counterpart. Even when I change the order of execution, there seems to be no difference in performance.
Let's first examine the faster snippet. This segment averages around 5 milliseconds using performance.now()
.
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);
Now let's contrast it with the slower code snippet, which surprisingly takes 100-200 milliseconds to run.
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);