data = [Array(685000)].map((_, id) => ({ id, data: Math.random() }))
const res = new Map(data.map(v => [v.id, v])).get(50)
const res = data.find(({ id }) => id === 50)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array to Map and find | |
Array.find |
Test name | Executions per second |
---|---|
Array to Map and find | 6.5 Ops/sec |
Array.find | 4287893.5 Ops/sec |
Let's break down the provided benchmark definition and test cases.
What is being tested?
The benchmark measures the performance of two different approaches:
Map
data structure from an array, where each element in the array becomes a key-value pair in the map.find()
method on an array to find the first element that satisfies a given condition.Options compared
The benchmark compares two different approaches:
find()
method on an array to find the first matching element.Pros and Cons
Other considerations
The benchmark does not consider other approaches, such as:
Array.prototype.filter()
instead of find()
.Library: Map data structure
A Map
is a built-in JavaScript data structure that stores key-value pairs. In this benchmark, it's used to store the transformed array data. The purpose of a map is to provide efficient lookup and iteration over its elements.
Special JS feature or syntax (None)
There are no special JavaScript features or syntax used in these test cases.
Benchmark preparation code
The provided script preparation code creates an array of 685,000 elements, where each element has an id
property and a random data
value. This data is then used to create the map and perform the find()
operation.
Other alternatives
If you want to explore other approaches or optimizations for this benchmark, consider the following:
Array.prototype.filter()
instead of find()
.