获得最大数组,sort()vs reduce()

时间:2017-11-27 11:11:06

标签: javascript

假设我们有一些数组,我想获得最大的元素。

array.sort((a, b) => b - a)[0]

array.reduce((a, b) => (a > b) ? a : b)

都会返回最大值。

问题是,首选哪一个?

对于我的项目的特定情况,我可以迭代100多个元素,100多次,我认为这些元素对于小的性能差异很重要。

1 个答案:

答案 0 :(得分:4)

array.reduce似乎更快..

var numbers = [];


function myFunction(item) {
 for (var i = 0 ; i<100000 ; i++)
 {
   numbers.push(i); 
 }


 var t0 = performance.now();
 var x = numbers.reduce((a, b) => (a > b) ? a : b);
 var t1 = performance.now()
 document.getElementById("timex").innerHTML = (t1 - t0) + " milliseconds";
 
 var t2 = performance.now();
 var y = numbers.sort((a, b) => b - a)[0];
 var t3 = performance.now();
 
 document.getElementById("timey").innerHTML = (t3 - t2) + " milliseconds";
 document.getElementById("reduce").innerHTML = x
 document.getElementById("sort").innerHTML = y
}
<html>
<body>

<p>Click the button to get the highest numbers in the array.</p>
<button onclick="myFunction()">Try it</button>

<p>Highest number (array.reduce): <span id="reduce"></span>  time taken : <span id="timex"></span></p>
<p>Highest number(array.sort): <span id="sort"></span> time taken:<span id="timey"></p>


<script>

</script>

</body>
</html>