const obj = {}
const map = new Map()
const n = 1000000;
for (let i = 0; i < n; i++) {
map.set(i, i);
}
const obj = {}
const map = new Map()
const n = 1000000;
for (let i = 0; i < n; i++) {
obj[i] = i;
}
const obj = {}
const map = new Map()
const n = Array(1000000).fill(0)
n.forEach((value, index) => {
map.set(index, index);
})
const obj = {}
const map = new Map()
const n = Array(1000000).fill(0)
n.forEach((value, index) => {
obj[index] = index;
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-loop + Map.set | |
for-loop + Object assignment | |
forEach + Map.set | |
forEach + Object assignment |
Test name | Executions per second |
---|---|
for-loop + Map.set | 9.4 Ops/sec |
for-loop + Object assignment | 43.4 Ops/sec |
forEach + Map.set | 5.4 Ops/sec |
forEach + Object assignment | 22.1 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared options, pros and cons of each approach, and other considerations.
Benchmark Description
The benchmark compares three approaches to assigning values to an object or a Map in JavaScript:
obj[i] = i;
).set()
method (e.g., map.set(i, i);
).set()
method.Libraries and Features Used
In this benchmark, only built-in JavaScript libraries and features are used. There are no external libraries or frameworks involved.
Approach Comparison
Here's a brief summary of each approach:
Map.set()
is an efficient way to add entries to a Map. This approach leverages the optimized implementation of the set()
method.Map.set()
within a forEach loop is an efficient way to add entries to a Map while iterating over an array. This approach combines the benefits of both methods.Other Considerations
When interpreting these results, keep in mind:
Map.set()
and array for forEach
methods might impact memory usage.Alternatives
If you're interested in exploring alternative approaches, consider:
while
, for...of
)Keep in mind that these alternatives might not be relevant to the specific problem being solved, and may introduce additional complexity.