var arrayStorage = new Array(5000).fill(0).map((v, i) => ({id: i, value: i}))
var mapStorage = new Map(arrayStorage.map((entry) => [entry.id, entry]))
var newItem = {id: 25, value: 222}
var index = arrayStorage.findIndex((item) => item.id === newItem.id)
arrayStorage = [arrayStorage.slice(0, index), newItem, arrayStorage.slice(index+1)]
mapStorage.delete(newItem.id)
arrayStorage = Array.from(mapStorage.values())
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array | |
Map |
Test name | Executions per second |
---|---|
Array | 33677.5 Ops/sec |
Map | 43872.0 Ops/sec |
Let's break down what is being tested in this benchmark.
Overview
The test measures the performance of two JavaScript operations on arrays and maps: finding an element by id using findIndex
, adding an element to the array, and deleting an element from the map. The goal is to compare the execution speed of these two approaches.
Options Compared
There are two options being compared:
arrayStorage
(a dense array) to find an element by id using findIndex
, add a new element to the array, and then update the array.mapStorage
(a map) to find an element by id using delete
on the map's values, convert the map's values to an array, and then update the array.Pros and Cons
Library and Syntax
The test case uses the Map
data structure from the ECMAScript standard library. The Map
object provides an efficient way to store key-value pairs, allowing for fast lookups using the has
method or the delete
method.
No special JavaScript features or syntax are used in this benchmark.
Considerations
Map
might be a better choice due to its efficiency. However, for smaller datasets or simple lookups, an array might be sufficient.Other Alternatives
If you're considering alternative approaches, here are a few options:
Set
, SortedSet
, or even custom implementations (e.g., binary search trees).Keep in mind that each approach has its pros and cons, and the best choice depends on your specific use case and requirements.