我正在尝试查看数值数组的 for 和 reduce 之间的性能差异,我可以看到总是我正在测量的第二个函数(无论是 for 还是 reduce)更快比第一个。我猜这与使用 Node 的数据缓存或线程池大小有关。这是代码:
process.env.UV_THREADPOOL_SIZE = 1;
let array = [
1,
23,
4,
5,
6,
7,
8,
7,
65,
4,
3,
23,
43,
2,
23,
32,
23,
23,
234,
243,
423,
432,
43,
23,
2,
23,
2,
23,
];
let sum = 0;
console.time('reduce');
sum = array.reduce((s, p) => (s += p), 0);
console.timeEnd('reduce');
sum = 0;
console.time('for');
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
console.timeEnd('for');
这段代码显示了不同的结果:
process.env.UV_THREADPOOL_SIZE = 1;
let array = [
1,
23,
4,
5,
6,
7,
8,
7,
65,
4,
3,
23,
43,
2,
23,
32,
23,
23,
234,
243,
423,
432,
43,
23,
2,
23,
2,
23,
];
let sum = 0;
console.time('for');
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
console.timeEnd('for');
sum = 0;
console.time('reduce');
sum = array.reduce((s, p) => (s += p), 0);
console.timeEnd('reduce');
我的意思是,如果你颠倒执行顺序,测得的结果是不一样的。
为了进行测试,我使用的是 Node v11.11.0
有什么想法吗?
编辑:我不是在寻找解释为什么 reduce 比 for 或类似的东西更快。我想知道为什么 nodejs 会产生这一系列操作的结果。
最佳答案
I mean, if you reverse the order of execution, the measured results are different.
这意味着:您的测试存在某种缺陷,或者结果非常随机,您无法根据它们做出判断。
更频繁地运行测试(几千次),然后取平均时间(通过它你平均掉其他代码片段的影响(你在多线程机器上运行),你强制引擎选择它最强大的优化)。
在此之前,无法判断哪一个更快。结果很可能是:没关系,都够快了。
关于javascript - 为什么第二个操作比第一个快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55923975/