var arr = [];
var max = -Infinity;
for (i = 0; i < 4096; i++) {
arr.push(Math.random() * i);
}
function mathMax (array) {
return Math.max.apply(Math, array);
}
max = Math.max.apply(Math, arr);
max = Math.max(arr);
for (let i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
for (let i = 0, len = arr.length; i < len; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] > max) {
max = arr[i];
}
}
for (const value of arr) {
if (value > max) {
max = value;
}
}
mathMax(arr)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Math.max.apply | |
Math.max with spread | |
basic for loop | |
for loop length caching | |
for loop reverse | |
for-of loop | |
Math.max.apply extracted into separate function |
Test name | Executions per second |
---|---|
Math.max.apply | 416659.7 Ops/sec |
Math.max with spread | 71629.2 Ops/sec |
basic for loop | 2321.8 Ops/sec |
for loop length caching | 3547.4 Ops/sec |
for loop reverse | 3446.5 Ops/sec |
for-of loop | 6471.1 Ops/sec |
Math.max.apply extracted into separate function | 4621156.0 Ops/sec |
I'll provide an explanation of the benchmark, options compared, pros and cons, and other considerations.
Benchmark Overview
The benchmark compares different approaches to find the maximum value in an array:
Math.max.apply
with .apply
Math.max
with spread operator (...
)Math.max.apply
functionOptions Compared
The benchmark compares seven different approaches:
Math.max.apply
with .apply
Math.max
with spread operator (...
)Math.max.apply
functionPros and Cons
Here's a brief pros and cons summary for each approach:
Math.max.apply
with .apply
:apply
method, which can be slower than other approaches.Math.max
with spread operator (...
):if
statements.length
.Math.max.apply
function:Other Considerations
The benchmark also takes into account the following:
Alternatives
If you're interested in exploring alternative approaches, consider the following:
Array.prototype.reduce()
instead of loops to find the maximum value.Keep in mind that these alternatives may not be as readable or maintainable as the approaches compared in the benchmark.