var i = 0, count = 100000, a;
var map = new Map();
var array = [];
var obj = {};
for (i = 0; i < count; i++) {
const randomValue = ~~(Math.random() * 100);
map.set(i, randomValue);
array.push({id: i, randomValue});
obj[i] = randomValue;
}
for (i = 0; i < count; i++) {
a = map.get(i);
}
for (i = 0; i < count; i++) {
a = array.find(el => el.id = i);
}
for (i = 0; i < count; i++) {
a = obj[i]
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map | |
array | |
obj |
Test name | Executions per second |
---|---|
map | 58.5 Ops/sec |
array | 58.5 Ops/sec |
obj | 61.2 Ops/sec |
Let's break down the provided benchmark and explain what is tested, the options compared, pros and cons of each approach, and other considerations.
Benchmark Definition
The benchmark measures the performance of three data structures in JavaScript:
Map
(a built-in JavaScript object)Array
(a built-in JavaScript array)obj
) created manuallyEach test case uses a different approach to access a value in each data structure.
Options Compared
The benchmark compares the performance of three options for accessing values in each data structure:
get()
methodfind()
method or direct indexing (e.g., array[i]
)obj[i]
)Pros and Cons
Here are some pros and cons of each approach:
get()
method; requires JavaScript engine support.Other Considerations
Alternatives
If you were to rewrite this benchmark, you could consider alternative data structures or access methods, such as:
WeakMap
instead of Map
Keep in mind that the choice of data structure and access method depends on the specific use case and requirements.