比较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
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短