var i = 0, count = 200000, a;
var map = new Map();
for (i = 0; i < count; i++) {
map.set(i + '_' + '_g' , i);
}
for (i = 0; i < count; i++) {
a = map.get(i + '_' + '_g');
}
for (i = 0; i < count; i++) {
let key = i + '_' + '_g';
if (map.has(key)) {
a = map.get(key);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map get | |
Map has get |
Test name | Executions per second |
---|---|
Map get | 25.3 Ops/sec |
Map has get | 20.6 Ops/sec |
I'll break down the provided benchmark definition and test cases to explain what's being tested, compare different approaches, and discuss pros and cons.
Benchmark Definition
The benchmark is designed to measure the performance of two ways to retrieve values from a Map
object in JavaScript:
get()
method: map.get(i + '_' + '_g')
has()
method followed by get()
: if (map.has(key)) { a = map.get(key); }
Script Preparation Code
The script preparation code creates a new Map
object named map
and populates it with 200,000 key-value pairs using the set()
method.
var i = 0, count = 200000, a;
var map = new Map();
for (i = 0; i < count; i++) {
map.set(i + '_' + '_g', i);
}
Html Preparation Code
The html preparation code is empty (null
), which means the benchmark doesn't involve any additional HTML setup or parsing.
Individual Test Cases
There are two test cases:
for (i = 0; i < count; i++) {
a = map.get(i + '_' + '_g');
}
This test case uses the get()
method to retrieve values from the map
object.
for (i = 0; i < count; i++) {
let key = i + '_' + '_g';
if (map.has(key)) {
a = map.get(key);
}
}
This test case uses the has()
method to check if a key exists in the map
object, and then retrieves the value using the get()
method.
Comparison of Approaches
The two approaches have different pros and cons:
has()
, which can be slower than directly accessing the value. However, it ensures that the key is present before attempting to retrieve its value.Library and Purpose
In this benchmark, there are no libraries used beyond the built-in Map
object in JavaScript.
Special JS Feature or Syntax
The has()
method was introduced in ECMAScript 2015 (ES6) as part of the standard. It's a convenient way to check if a key exists in an object without using the in
operator or bracket notation ([key]
).
Other Alternatives
There are alternative ways to retrieve values from a map-like object, such as:
get()
method with a default value (e.g., map.get(key) || defaultValue
)In general, the choice of approach depends on the specific use case and performance requirements.