Math.max 或 array.reduce 之内的总和在性能方面更好
Math.max or sum within array.reduce which is better in terms of performance
我们一直在解决一个问题来检查数组是否有任何值 >0 的项目,但现在有人有 2 种方法使用 array.reduce
一个。使用 Math.max(一开始是错误的,但顺其自然)
b。使用初始值为 0 的简单 reduce 方法;
我不确定如何使用 jsperf.com 进行检查,因此在 console.time()
下面的代码片段中创建并在 chrome 控制台中进行了检查,但问题是每次结果都以这样的方式更改有时 a 比 b 花费的时间少,而有时 b 比 花费的时间少]a
每个 运行 区块的结果各不相同。
请指导我证明哪个更好
这是我要测试的代码段
{
const input = [0,10,20,30,8,0,0];
const sumOutput = () => input.reduce( (c, a) => c +=a , 0);
const maxOutput = () => input.reduce( (a,b) => Math.max(a,b));
console.time('sum');
input.forEach( () => sumOutput() );
console.timeEnd('sum');
console.log(' ======' );
console.time('max');
input.forEach( () => maxOutput() );
console.timeEnd('max');
}
你的时间会有所不同,因为 JavaScript 它的运行方式有点不稳定。如果垃圾收集器在您的代码期间触发或毫秒时间没有从 0 开始,您的结果将会关闭。
最简单的解决方案是使用循环扩展测试,因为这样可以减少计时不准确的影响:
var tests = 1000000;
var input = [0, 10, 20, 30, 8, 0, 0];
var sumOutput = function() {
return input.reduce(function(c, a) {
return c += a;
}, 0);
};
var maxOutput = function() {
return input.reduce(function(a, b) {
return Math.max(a, b);
});
};
console.time('sum');
var i = tests;
while (i--) {
input.forEach(function() {
return sumOutput();
});
}
console.timeEnd('sum');
console.log(' ======');
console.time('max');
var i = tests;
while (i--) {
input.forEach(function() {
return maxOutput();
});
}
console.timeEnd('max');
我们一直在解决一个问题来检查数组是否有任何值 >0 的项目,但现在有人有 2 种方法使用 array.reduce
一个。使用 Math.max(一开始是错误的,但顺其自然)
b。使用初始值为 0 的简单 reduce 方法;
我不确定如何使用 jsperf.com 进行检查,因此在 console.time()
下面的代码片段中创建并在 chrome 控制台中进行了检查,但问题是每次结果都以这样的方式更改有时 a 比 b 花费的时间少,而有时 b 比 花费的时间少]a
每个 运行 区块的结果各不相同。
请指导我证明哪个更好
这是我要测试的代码段
{
const input = [0,10,20,30,8,0,0];
const sumOutput = () => input.reduce( (c, a) => c +=a , 0);
const maxOutput = () => input.reduce( (a,b) => Math.max(a,b));
console.time('sum');
input.forEach( () => sumOutput() );
console.timeEnd('sum');
console.log(' ======' );
console.time('max');
input.forEach( () => maxOutput() );
console.timeEnd('max');
}
你的时间会有所不同,因为 JavaScript 它的运行方式有点不稳定。如果垃圾收集器在您的代码期间触发或毫秒时间没有从 0 开始,您的结果将会关闭。
最简单的解决方案是使用循环扩展测试,因为这样可以减少计时不准确的影响:
var tests = 1000000;
var input = [0, 10, 20, 30, 8, 0, 0];
var sumOutput = function() {
return input.reduce(function(c, a) {
return c += a;
}, 0);
};
var maxOutput = function() {
return input.reduce(function(a, b) {
return Math.max(a, b);
});
};
console.time('sum');
var i = tests;
while (i--) {
input.forEach(function() {
return sumOutput();
});
}
console.timeEnd('sum');
console.log(' ======');
console.time('max');
var i = tests;
while (i--) {
input.forEach(function() {
return maxOutput();
});
}
console.timeEnd('max');