DEV Community

Discussion on: 1 line of code: How to get highest numeric item of an Array

Collapse
 
jrop profile image
Jonathan Apodaca

I'm curious how the performance compares to:

arr.reduce((prev, curr) => Math.max(prev,curr))
Enter fullscreen mode Exit fullscreen mode

Especially in the case of large arrays, I'm not sure what the implications are (if any) to spreading a large array to function arguments

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Try this - the first method seems to be about 10 times as fast

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Interestingly, if you switch to a typed array, the results are reversed - reduce is 10 times as fast on Firefox, and nearly twice as fast on Chrome

Thread Thread
 
jrop profile image
Jonathan Apodaca

And unsurprisingly, this is even faster:

let m = Number.NEGATIVE_INFINITY;
for (const x of data) {
  m = Math.max(x, m);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
martinkr profile image
Martin Krause • Edited

Thank you both for the performance analysis, it's very helpful to have these additional details :)