const object = (id) => ({ a: () => id, b: "id-" + id, });
const map = new Map();
const arr = [];
const max = 100;
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 | 5426556.5 Ops/sec |
Map.get | 34235816.0 Ops/sec |
The provided JSON represents a JavaScript benchmark that compares the performance of two data structures: a Map
and an Array
. Here's a detailed explanation of the benchmark setup, the tests conducted, and the implications for software engineers.
Setup:
Map
is used to store key-value pairs where each key is a number, and each value is an object generated by the object
function.Array
is also populated with the same objects but structured differently (each object contains an id
property along with the other properties).Purpose of Data Structures:
id
for identification. It is less efficient for lookups compared to a Map
, especially as the size of the array increases.The benchmark includes two specific tests:
Array.findIndex:
const id = rng(); const index = arr.findIndex((obj) => obj.id === id);
Array
can find the index of an object with a specific id
. The findIndex
method iterates over the array until it finds an element that matches the criteria, which can take linear time (O(n)) in the worst case.Map.get:
const id = rng(); const value = map.get(id);
Map
can retrieve a value associated with a given key. The get
method performs lookups in constant time (O(1)), making it generally faster than searching through an array.The results of the benchmark show a significant difference between the two tests:
34,235,816
executions per second.5,426,556.5
executions per second.Map
Array
map
, filter
, and reduce
that are beneficial for a variety of operations.Map
is usually the better option.Array
may suffice.Other alternatives to consider might include:
In conclusion, the benchmark effectively demonstrates the performance advantage of using Map
over Array
for certain operations, particularly those involving frequent key-based lookups. Each data structure has its ideal use case, and software engineers should choose based on the specific requirements of their application.