var arr = [Array(1000)].map(() => Math.floor(Math.random() * 100000));
return Math.max(arr);
return arr.reduce((maxi, curr) => maxi < curr ? curr : maxi, -1);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Math.max | |
Find |
Test name | Executions per second |
---|---|
Math.max | 625754.3 Ops/sec |
Find | 1528388.6 Ops/sec |
Overview of the Benchmark
The provided benchmark measures the performance difference between two approaches to find the maximum value in an array: using the built-in Math.max
function and iterating through the array manually.
Approaches Compared
There are two test cases:
Math.max
function, which is a part of the JavaScript standard library. It takes multiple arguments and returns the largest value among them.-1
) and updates it if it finds a larger value in the array.Pros and Cons of Each Approach
Math.max
.Library Used
None.
Special JavaScript Features/Syntax
There are no special features or syntax used in this benchmark. It only focuses on demonstrating two simple approaches to finding the maximum value in an array.
Other Alternatives
If you wanted to measure alternative approaches, some possible options could include:
reduce()
instead of manual iteration.Keep in mind that these alternatives would require significant changes to the benchmark setup and test cases.
Benchmark Preparation Code Explanation
The provided script preparation code generates an array of 1000 random numbers using Array.prototype.map()
and assigns it to the variable arr
. This ensures that each test case starts with a fresh, randomized array.
The individual test cases are defined as JavaScript functions that return the desired result: either using Math.max
or implementing the manual iteration approach.