var i = 0, count = 20000, 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 | 297.4 Ops/sec |
Map has get | 231.3 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The provided JSON represents a benchmark test that compares two approaches: Map.get()
and Map.has() + Map.get()
. The test is designed to measure the performance difference between these two methods in retrieving values from a large Map object.
Script Preparation Code
The script preparation code creates a new Map object, map
, and populates it with 20,000 key-value pairs using the set()
method. The keys are generated dynamically using string concatenation (i + '_' + '_g'
).
var i = 0, count = 20000, a;
var map = new Map();
for (i = 0; i < count; i++) {
map.set(i + '_' + '_g', i);
}
Html Preparation Code
The HTML preparation code is null, indicating that no specific HTML structure or content is required for this benchmark.
Test Cases
There are two test cases:
map.get()
method to retrieve values from the Map object.for (i = 0; i < count; i++) {
a = map.get(i + '_' + '_g');
}
map.has()
method to check if a key exists in the Map, and then retrieves the value using map.get()
.for (i = 0; i < count; i++) {
let key = i + '_' + '_g';
if (map.has(key)) {
a = map.get(key);
}
}
Library: None
The benchmark does not use any external libraries, which is good for isolating the test results and ensuring that the comparison between Map.get()
and Map.has() + Map.get()
is accurate.
Special JS Features or Syntax: None
There are no special JavaScript features or syntax used in this benchmark. The code uses standard JavaScript syntax and features to create the Map object, populate it with data, and measure performance.
Performance Comparison
The benchmark measures the execution rate of each test case using the ExecutionsPerSecond
metric. This value represents the number of times each test case is executed per second on a given device.
In this benchmark, Mobile Safari 16 on an iPhone running iOS 16.4.1 achieved:
These results indicate that Map.get()
is slightly faster than Map.has() + Map.get()
.
Alternatives
Other alternatives for benchmarking JavaScript performance include:
performance.now()
or PerformanceObserver
that provide more accurate timing measurements.Keep in mind that the choice of alternative depends on the specific use case, desired level of control, and performance requirements.