var myMap = new Map();
for (let i = 0; i < 10000; i++) {
myMap.set(i,i);
}
function someFn(i) {
return i * 3 * 8;
}
myMap.forEach(function (key, value){
someFn(value);
})
for (let [key, value] of myMap) {
someFn(value);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Foreach | |
Loop |
Test name | Executions per second |
---|---|
Foreach | 534.0 Ops/sec |
Loop | 541.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Setup
The benchmark creates a JavaScript Map
object, myMap
, and populates it with 10,000 key-value pairs. It also defines a function, someFn
, that takes an integer value as input and returns its multiplication by 3 and 8.
Test Cases
There are two test cases:
forEach
method to iterate over the myMap
object. The forEach
method executes a provided function for each key-value pair in the map.for
loop with destructuring syntax (for (let [key, value] of myMap)
) to iterate over the myMap
object.Libraries and Features
In this benchmark, the following JavaScript libraries or features are used:
Map
: A built-in JavaScript object that stores key-value pairs. It's used as a data structure in both test cases.Destructuring syntax (
for (let [key, value] of myMap)`) : This is a modern JavaScript feature introduced in ECMAScript 2015 (ES6). It allows extracting multiple values from an iterable (such as a map) into individual variables.Options Compared
The two test cases compare the performance of using forEach
versus traditional loops with destructuring syntax to iterate over the myMap
object.
Pros and Cons
forEach
.forEach
.Other Considerations
When writing performance benchmarks, consider the following:
Alternatives
If you wanted to add more test cases, you could consider the following alternatives:
forEach
to an array-like object (like a map) and returns the original array-like object.Keep in mind that adding alternative test cases may require significant changes to your benchmark, including modifying the script preparation code or data generation.