var i = 0, count = 1000, a;
var map = new Map();
for (i = 0; i < count; i++) {
if (Math.random() > 0.5) {
map.set(i, i * i);
}
}
let b;
for (i = 0; i < count; i++) {
a = map.get(i);
if (a) {
b = a;
}
}
let b;
for (i = 0; i < count; i++) {
if (map.has(i)) {
b = map.get(i);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map 1 | |
Map 2 |
Test name | Executions per second |
---|---|
Map 1 | 57938.0 Ops/sec |
Map 2 | 61088.2 Ops/sec |
Let's break down what is being tested in this benchmark and the pros/cons of different approaches.
Benchmark Definition
The benchmark measures the performance difference between two ways to retrieve values from a Map
object:
map.get()
map.has()
followed by map.get()
Script Preparation Code
The script creates a new Map
object and populates it with 1000 key-value pairs, where each value is the square of its corresponding key.
Html Preparation Code
There is no HTML preparation code provided, so we'll focus on the JavaScript aspects only.
Individual Test Cases
We have two test cases:
let b;
for (i = 0; i < count; i++) {
a = map.get(i);
if (a) {
b = a;
}
}
This code uses map.get()
to retrieve the value associated with each key and assigns it to b
only if the value is not null or undefined.
let b;
for (i = 0; i < count; i++) {
if (map.has(i)) {
b = map.get(i);
}
}
This code uses map.has()
to check if each key exists in the map and then uses map.get()
to retrieve its value, assigning it to b
.
Pros/Cons of Different Approaches
map.get()
undefined
, which can lead to unnecessary iterations in some cases.map.has()
followed by map.get()
Library and Purpose
In this benchmark, no external libraries are used. The Map
object is a built-in JavaScript data structure.
Special JS Features/Syntax
None of the test cases use any special JavaScript features or syntax that would affect their execution.
Other Alternatives
If you wanted to test alternative approaches, you could consider:
Object.keys()
and at()
(ECMAScript 2022) to iterate over map entriesMap
vs. WeakMap
map.get()
vs. map.has()
on memory usage or other factorsKeep in mind that these alternatives might not be directly relevant to the specific use case being tested and may introduce additional complexity.