var map = new Map();
for (var i = 0; i < 10000; i++) {
map[Math.random()] = Math.random();
}
for (var [key, value] of map.entries()) {
key
value
}
map.forEach(function(value, key) {
key
value
}, map)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For Entries | |
Foreach |
Test name | Executions per second |
---|---|
For Entries | 64019900.0 Ops/sec |
Foreach | 43921876.0 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Definition
The benchmark defines two test cases:
Map
object and populates it with 10,000 key-value pairs using the Math.random()
function to generate random keys.for...of
loop syntax, which was introduced in ECMAScript 2017 (ES7). The test case iterates over the map's entries and logs each key and value.forEach()
method with a callback function.Options Compared
The benchmark compares the performance of two approaches:
for...of
loop syntax to iterate over the map's entries.forEach()
method with a callback function.Pros and Cons
Library
The Map
object is a built-in JavaScript data structure that stores key-value pairs. It was introduced in ECMAScript 2015 (ES6) as part of the standard library.
Special JS Feature/Syntax
No special syntax or features are used in this benchmark, making it accessible to a wide range of developers and environments.
Other Considerations
When writing microbenchmarks like this one, consider the following:
Alternatives
If you wanted to write similar benchmarks using different approaches, consider the following alternatives:
Array.prototype.forEach()
instead of the traditional forEach()
method with a callback function.Set
or arrays, when used for iteration.Keep in mind that each alternative will introduce new variables and complexities to consider when writing a benchmark.