var items = [{
val: 7
},
{
val: 9
},
{
val: 8
},
{
val: 3
},
{
val: 12
},
{
val: 34
},
{
val: 7
},
{
val: 512
}
]
Math.min(items.map(item => item.val))
items.reduce((acc, current) => acc < current.val ? acc : current.val)
items.reduce((acc, current) => acc < current.val ? acc : current.val, items[0].val)
items.reduce((acc, current) => acc > current.val ? current.val : acc)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map and Math.min | |
Reduce without initial value | |
Reduce with initial value | |
Reduce without initial value 2 |
Test name | Executions per second |
---|---|
Map and Math.min | 3553170.2 Ops/sec |
Reduce without initial value | 5112774.0 Ops/sec |
Reduce with initial value | 3686865.5 Ops/sec |
Reduce without initial value 2 | 1440307.1 Ops/sec |
I'll break down the provided JSON and explain what's being tested, compared, and considered.
Benchmark Definition
The benchmark is defined by two scripts: one for preparing data (Script Preparation Code
) and none for HTML preparation. The prepared data consists of an array of objects with a single property val
. The purpose of this benchmark is to measure the performance of different approaches to find the minimum value in an array of objects.
Individual Test Cases
There are four test cases, each defining a different approach:
items
array to extract the val
property from each object using item => item.val
, and then uses Math.min()
to find the minimum value.reduce()
method with an initial value of undefined
(which will be considered as -Infinity
) to iterate through the array and update the accumulator (acc
) if a smaller value is found.items[0].val
) as the initial value.2
instead of -Infinity
.Comparison
The comparison being made is between these four approaches to find the minimum value in the array:
Pros and Cons:
map()
and Math.min()
).reduce()
without an initial value.Other Considerations
map()
followed by Math.min()
may incur additional overhead compared to other approaches.reduce()
with an initial value can lead to better cache locality and reduced overhead compared to other approaches.Browser-Specific Notes
The benchmark results indicate that Chrome 84 on a Mac OS X 10.15.4 desktop is the fastest browser, followed closely by another instance of the same browser. The performance difference between reduce without initial value and reduce with initial value suggests that starting with a known good value can be beneficial.
Library Usage
There are no specific libraries used in this benchmark, only built-in JavaScript functions (map()
, Math.min()
, reduce()
).
No special JavaScript features or syntax are being tested in this benchmark.