const object = (id) => ({ a: () => id, b: "id-" + id, });
const map = new Map();
const arr = [];
const max = 100_000;
for (let i = 0; i < max; i++) {
map.set(i, object(i));
arr.push({ id: i, object(i) });
}
const rng = () => Math.floor(Math.random() * max);
const id = rng();
const index = arr.findIndex((obj) => obj.id === id);
const id = rng();
const value = map.get(id);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.findIndex | |
Map.get |
Test name | Executions per second |
---|---|
Array.findIndex | 2175.2 Ops/sec |
Map.get | 255799296.0 Ops/sec |
The benchmark provided compares the performance of two data structure operations in JavaScript: retrieving a value from a Map
and finding an index of an object in an Array
. This comparison is essential for understanding the efficiency of different approaches to data management in JavaScript, particularly when considering performance in applications dealing with large datasets.
Map
Map
is a collection of key-value pairs where keys can be of any type, and each key is unique. In this benchmark, a Map
is used to store objects indexed by numerical keys (0 to 99,999).Array
Array
in JavaScript is a list-like object that allows indexed access to its elements. In this benchmark, an Array
of objects, each containing an id
property and other associated properties, is created.id
in this case) requires scanning the entire array, resulting in O(n) time complexity.Array.findIndex
id
using the findIndex
method. This method will traverse the array until it finds a match.Map.get
id
directly from the map. The get
method provides direct access to the value by its key.Map
for key-based access.Map
and Array
, consider the access patterns. If frequent lookups by a unique identifier are needed, Map
is preferable. For scenarios where order is crucial or where you need to iterate through values, an Array
may be more suitable.Array
for ordered data and a Map
for fast lookups, providing a balance of performance and functionality.Map
, but with limitations, such as only allowing strings as keys and not maintaining the order of insertion.Set
serves a distinct purpose by storing unique values and providing O(1) complexity for checks of presence, but it doesn’t store key-value pairs.Map
for lookups and maintaining an array structure for other operations (e.g., ordered iteration) can provide an optimal solution.Overall, the benchmark clearly illustrates the advantages of using a Map
for efficient data retrieval when performance is crucial, especially as the dataset scales. This understanding is vital for software engineers when designing systems that require optimal data management and retrieval strategies.