var myMap = new Map([[x => x, 'a'], [x => x, 'b'], [x => x, 'c'], [x => x, 'd']]);
myMap.forEach((payload, callback) => {
callback(payload);
myMap.delete(callback);
});
for (const [callback, payload] of myMap) {
callback(payload);
myMap.delete(callback);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
forEach | |
for...of |
Test name | Executions per second |
---|---|
forEach | 14205932.0 Ops/sec |
for...of | 15749930.0 Ops/sec |
The provided JSON represents a benchmark test case for JavaScript microbenchmarks on the MeasureThat.net website. The test aims to compare the performance of two approaches for iterating over and modifying elements in a Map data structure.
Overview
A Map is a built-in JavaScript object that stores key-value pairs, where each key is unique and maps to a specific value. In this benchmark, we're comparing two ways to iterate over the key-value pairs in a Map:
Options compared
The benchmark compares the performance of these two approaches:
Pros and Cons
Pros:
Cons:
Pros:
Cons:
Library
There is no external library used in this benchmark. The Map data structure is a built-in JavaScript object.
Special JS feature or syntax
None are mentioned explicitly, but =>
is used as an arrow function syntax (i.e., shorthand for function expressions).
Benchmark preparation code
The script preparation code creates a new Map instance with four key-value pairs and assigns it to the variable myMap
. The HTML preparation code is empty.
Individual test cases
There are two test cases:
myMap
using the forEach
method.myMap
using the for...of statement.Latest benchmark result
The latest benchmark results show that the for...of approach is slightly faster than the forEach approach, with an average of 14,206,932 executions per second (in Chrome 106 on a Mac OS X 10.15.7 desktop) compared to 14,245,993 executions per second.
Other alternatives
If you want to explore other approaches for iterating over Map elements, consider the following:
Iterator
class from JavaScript's built-in Symbol.iterator
protocol.Keep in mind that these alternatives might have trade-offs in terms of code readability, compatibility with older browsers, or overall performance.