比较 forEach() 和 reduce() 来求和一个包含数字的 JavaScript 数组所花费的时间。


我们需要比较 ES6 函数 forEach() 和 reduce() 分别花费的时间,用于计算一个包含大量数字的数组的和。

由于我们这里不可能有大量数组,我们将通过执行大量次(迭代)求和操作来模拟数组的大小

示例

让我们编写此代码 −

const arr = [1, 4, 4, 54, 56, 54, 2, 23, 6, 54, 65, 65];
const reduceSum = arr => arr.reduce((acc, val) => acc + val);
const forEachSum = arr => {
   let sum = 0;
   arr.forEach(el => sum += el);
   return sum;
};
const iterations = 1000000000;
console.time('reduce');
for(let i = 0; i < iterations; i++){
   let sumReduce = reduceSum(arr);
};
console.timeEnd('reduce');
console.time('forEach');
for(let j = 0; j < iterations; j++){
   let sumForEach = forEachSum(arr);
};
console.timeEnd('forEach');

输出

控制台中的输出如下 −

reduce: 19.058s
forEach: 45.204s

因此,Array.prototype.reduce() 花费的时间与 Array.prototype.forEach 花费的时间之比约为  1 : 1.4

更新时间: 15-Sep-2020

404 次浏览

开始你的 职业

完成课程获得认证

开始
广告
© . All rights reserved.