var arr = [];
var max = -Infinity;
for (i = 0; i < 4096; i++) {
arr.push(Math.random() * i);
}
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;
}
}
--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 |
Test name | Executions per second |
---|---|
Math.max.apply | 52504.6 Ops/sec |
Math.max with spread | 52354.1 Ops/sec |
basic for loop | 144585.6 Ops/sec |
for loop length caching | 155074.0 Ops/sec |
for loop reverse | 144456.4 Ops/sec |
for-of loop | 21305.4 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Description
The benchmark compares the performance of different ways to find the maximum value in an array:
Math.max.apply(Math, arr)
...arr
)arr.length
on each iteration)Pros and Cons of Different Approaches
Math.max.apply
, but more concise and modern-lookingarr.length
lookupsLibrary Usage
None of the test cases use external libraries.
Special JavaScript Features or Syntax
...arr
): used in tests 2 and 3 to pass an array as individual arguments to Math.max
.arr.length
is stored in a variable (len
) and reused on each iteration.Alternatives
If you wanted to write this benchmark using a different language or framework, some alternatives could be:
max
function and list comprehensionsCollections.max
method and enhanced for loopsHowever, JavaScript is well-suited for this benchmark due to its dynamic nature, ease of use, and wide adoption.