var i = 0, count = 1000, a;
var map = new Map();
for (i = 0; i < count; i++) {
if (Math.random() > 0.99) {
map.set(i, i * i);
}
}
for (i = 0; i < count; i++) {
a = map.get(i);
}
for (i = 0; i < count; i++) {
if (map.has(i)) {
a = map.get(i);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map 1 | |
Map 2 |
Test name | Executions per second |
---|---|
Map 1 | 5338.0 Ops/sec |
Map 2 | 8771.2 Ops/sec |
This benchmark is focused on comparing two different methods of accessing values stored in a JavaScript Map
object. It tests the performance of these methods to understand their efficiency in terms of execution speed.
Test Name: The benchmark is named "Map get VS Map has get," indicating it is comparing two approaches related to retrieving data from a Map
.
Script Preparation: The preparation code creates a Map
and populates it with up to 1000 entries. The number of entries is determined randomly, which means some keys will not have corresponding values in the map. The map.set(i, i * i)
line sets the key-value pairs, where each key i
is associated with i
squared.
Test Case 1: Map 1
for (i = 0; i < count; i++) {
a = map.get(i);
}
Map
using the get
method for every integer from 0 to count - 1
. If the key exists, it returns the corresponding value, but if it doesn't, it returns undefined
.Test Case 2: Map 2
for (i = 0; i < count; i++) {
if (map.has(i)) {
a = map.get(i);
}
}
map.has(i)
. If the key is present in the Map
, it retrieves the value using get
. This method potentially avoids unnecessary calls to get
for keys that do not exist, which could be a performance improvement over the first method.Pros and Cons:
Map 1 (Direct get
call):
undefined
, especially if the map is sparsely populated.Map 2 (Using has
before get
):
get
method calls that will yield undefined
.has
) for each iteration, which can add up depending on the key distribution, although this overhead might be offset by the savings from avoiding unnecessary get
calls.From the benchmark results:
has
before get
) showed a higher execution count per second (8771.16) compared to Map 1 (5338.04). This indicates that the first approach is less efficient than the second when accessing values in the Map
, particularly in scenarios with many non-existent keys.Alternatives to Map
:
WeakMap
might be a good option, but it has different use cases compared to Map
.Other Access Methods:
In conclusion, the benchmark demonstrates the performance implications of different access patterns with Map
objects, providing insights into effective strategies for efficient data retrieval in JavaScript applications.