var array = [];
for (var i = 0; i < 10000; i++) {
array.push({
value: Math.random() * 1000000,
});
}
var max = Math.max.apply(Math, array.map(x => x.value));
var max = Math.max(array.map(x => x.value))
var max = array.reduce((prev, current) => (prev && prev.value > current.value) ? prev : current).value;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
1 | |
2 | |
3 |
Test name | Executions per second |
---|---|
1 | 5964.0 Ops/sec |
2 | 6393.9 Ops/sec |
3 | 19646.6 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Definition
The benchmark is designed to measure how fast different approaches can find the maximum value of a property in an array of objects.
Options Compared
There are three options compared:
Math.max.apply(Math, array.map(x => x.value))
: This method uses the map()
function to create a new array with the values of each object's property, and then applies the Math.max()
function to find the maximum value.Math.max(...array.map(x => x.value))
: This method is similar to the previous one, but it uses the spread operator (...
) to pass the mapped array as separate arguments to the Math.max()
function.array.reduce((prev, current) => (prev && prev.value > current.value) ? prev : current).value
: This method uses the reduce()
function to iterate over the array and find the maximum value.Pros and Cons of Each Approach
Math.max.apply(Math, array.map(x => x.value))
:Math.max(...array.map(x => x.value))
:apply()
, and avoids creating a new array.array.reduce((prev, current) => (prev && prev.value > current.value) ? prev : current).value
:Library and Purpose
In none of these examples is a specific library used. However, Math.max()
is a built-in JavaScript function that can be used for this purpose.
Special JS Features or Syntax
The benchmark uses the following features:
...
): Used in option 2 to pass the mapped array as separate arguments to Math.max()
.Other Alternatives
If you're looking for alternative approaches, here are a few:
array.forEach()
+ Math.max()
: Iterate over the array using forEach()
and call Math.max()
on each element.map()
, then reduce()
: Create a new array with the mapped values, and then use reduce()
to find the maximum value.Keep in mind that these alternatives may have different performance characteristics or trade-offs compared to the original options.