array.reduce中的Math.max或sum在性能方面更好

时间:2018-06-20 09:09:54

标签: javascript performance-testing

我们一直在解决一个问题,检查数组是否具有值大于0的任何项目,但现在有人使用array.reduce

有2种方法

a。使用Math.max(一开始是错误的,但顺其自然)

b。使用初始值为0的简单reduce方法;

我不确定如何检查使用console.time()在代码段下面创建的jsperf.com,并在chrome控制台中进行了检查,但是问题是每次更改结果的方式有时都是 a < / em>花费的时间少于 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');

 }

1 个答案:

答案 0 :(得分:0)

您的时间各不相同,因为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');