admin管理员组文章数量:1405392
Assume we have some array and I want to get the maximum of the elements.
array.sort((a, b) => b - a)[0]
and
array.reduce((a, b) => (a > b) ? a : b)
will both return the maximum.
The question is, which one is preferred?
For a specific case of my project, I could be iterating over 100+ elements, 100+ times which I thought would be big enough to matter for the small performance difference.
Assume we have some array and I want to get the maximum of the elements.
array.sort((a, b) => b - a)[0]
and
array.reduce((a, b) => (a > b) ? a : b)
will both return the maximum.
The question is, which one is preferred?
For a specific case of my project, I could be iterating over 100+ elements, 100+ times which I thought would be big enough to matter for the small performance difference.
Share Improve this question asked Nov 27, 2017 at 11:11 Jun ParkJun Park 5581 gold badge7 silver badges20 bronze badges 7- I think array.reduce is faster. Sorting always needs more operations behind – Faly Commented Nov 27, 2017 at 11:14
-
4
I would prefer
Math.max(...arr)
myself – Karl Reid Commented Nov 27, 2017 at 11:14 - 2 reduce is O(n), sort is O(nlogn). – Nina Scholz Commented Nov 27, 2017 at 11:14
- 1 @KarlReid Math.max is not remended for large array. – priyadarshi swain Commented Nov 27, 2017 at 11:21
- 1 @NinaScholz I didn't know that. Sounds like reduce is the winner then. :D – Jun Park Commented Nov 27, 2017 at 11:22
2 Answers
Reset to default 7array.reduce seems faster..
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>
I tried to check performance and this is result, hope you know more about them.
本文标签: javascriptGetting the maximum of arraysort() vs reduce()Stack Overflow
版权声明:本文标题:javascript - Getting the maximum of array, sort() vs reduce() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744219236a2595784.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论