我在几天后发现了一些关于stackoverflow帖子的讨论(抱歉我记不起帖子),有人建议forEach与for循环相比有时间损失(即需要更多时间来运行)。为了测试这个,我写了下面的代码:
function testPrototypeUse(){
/*
* Checks whether there is a performance penalty in
* invoking prototype methods from builtin objects
* specifically, forEach from Array.prototype
*/
'use strict';
const max_size = 3600000;
let blob = [];
let txt = '';
for(let i=0; i<max_size; i++){
blob.push(i);
}
console.log(''+ max_size +' checks for \'for\' and forEach');
console.log('Initial blob size test: ' + blob.length);
let start = process.hrtime();
Array.prototype.forEach.call(blob, function(n){
txt += n;
});
let elapsed = process.hrtime(start);
console.log('Array.prototype.forEach.call took: Total: '+ (elapsed[0]) +' s, ' + parseFloat(elapsed[1]/10e6).toPrecision(4) +' ms ');
// delete txt; throws Syntax Error: cannot delete unqualified identifier
txt = '';
console.log('Blob size test before for: ' + blob.length);
start = process.hrtime();
for(let i=0; i<blob.length; i++){
txt += i;
}
elapsed = process.hrtime(start);
console.log('For loop took: Total: '+ (elapsed[0]) +' s, ' + parseFloat(elapsed[1]/10e6).toPrecision(4) +' ms ');
txt = '';
console.log('Blob size test before blob.forEach: ' + blob.length);
start = process.hrtime();
blob.forEach(function(i){ txt+=i; });
elapsed = process.hrtime(start);
console.log('blob.forEach took: Total: '+ (elapsed[0]) +' s, ' + parseFloat(elapsed[1]/10e6).toPrecision(4) +' ms ');
}
我在运行测试之前的初步想法如下:
在运行测试后,值为1000000 - 3600000,我得到的结果是:
现在,看到前两个结果与我的预期相同(尽管,性能损失超过了我对prototype.forEach的预期而不是)。在blob.forEach
的情况下,惩罚甚至更高(如果我是对的,因为编译器必须遵循整个原型链到最后的第二个,Array)。我想知道是否有任何可用的优化可用于提高Array.prototype.forEach.call的性能?我一直在我的代码中使用它们代替循环,看到差异,我担心代码必须在高压力环境下运行时会受到惩罚。
提前多多感谢。