const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Math.max.apply(null, array);
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Math.max(array);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
apply | |
spread |
Test name | Executions per second |
---|---|
apply | 8350489.0 Ops/sec |
spread | 8122875.0 Ops/sec |
This benchmark compares two ways to find the maximum value in an array using JavaScript: Math.max.apply(null, array)
and Math.max(...array)
.
Options Compared:
Math.max.apply(null, array)
: This method uses the apply
function to call Math.max
with the array as an argument list. The null
passed as the first argument indicates that we don't want to use a specific object's context for the function call.
Math.max(...array)
: This method utilizes the spread operator (...
) to expand the array into individual arguments when calling Math.max
.
Pros and Cons:
apply
:
spread
:
Other Considerations:
Math.max
. The benchmark results you provided might show minor variations, but those could be attributed to browser optimizations or other environmental factors rather than a fundamental difference in the approaches.Alternatives:
Array.prototype.reduce()
: You could use the reduce method to find the maximum value iteratively within the array:
const max = array.reduce((maxVal, current) => (current > maxVal ? current : maxVal), array[0]);
Array.prototype.sort()
: Although not as direct, you could sort the array and take the last element:
const sortedArray = array.sort((a, b) => a - b);
const max = sortedArray[sortedArray.length - 1];
Let me know if you have any other questions or would like to explore specific benchmark results in more detail!