比较 JavaScript 中 forEach() 和 reduce() 对数字数组求和的用法。

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/4 16:12:17

我们需要比较 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


相关文章


有用资源