var mapForEach = new Map();
var arr = [];
var mapToArr = new Map();
for (let i=0; i<100000; i++) {
mapForEach.set(i, i);
arr.push(i);
mapToArr.set(i, i);
}
mapForEach.forEach(console.log);
arr.forEach(console.log);
Array.from(mapToArr.values()).forEach(console.log);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map.prototype.forEach | |
Array.prototype.forEach | |
Array.from(Map.prototype.values()).forEach |
Test name | Executions per second |
---|---|
Map.prototype.forEach | 3.7 Ops/sec |
Array.prototype.forEach | 4.3 Ops/sec |
Array.from(Map.prototype.values()).forEach | 4.2 Ops/sec |
Let's dive into the benchmark.
What is being tested?
The provided JSON represents a microbenchmark test that compares the performance of three different approaches:
Map.prototype.forEach
Array.prototype.forEach
Array.from(Map.prototype.values()).forEach
These approaches are compared in terms of their execution speed, measured in executions per second.
Options compared:
Map.prototype.forEach
: This method is used to iterate over the values of a Map object.Array.prototype.forEach
: This method is used to iterate over an array of elements. Both Map.prototype.forEach
and Array.prototype.forEach
use similar syntax, but forEach
on arrays is generally faster because it doesn't require creating an iterator object like Map.prototype.forEach
does.Array.from(Map.prototype.values()).forEach
: This approach involves converting the values of a Map to an array using Array.from()
and then calling forEach()
on that array.Pros and Cons:
Map.prototype.forEach
:Array.prototype.forEach
because it creates an iterator object.Array.prototype.forEach
:forEach
.Array.from(Map.prototype.values()).forEach
:forEach
. Suitable for large datasets.Array.prototype.forEach
.Library Usage:
console.log
as the callback function for the forEach()
method. This is a built-in JavaScript function and does not require any external libraries.Special JS Features or Syntax:
for...of
loop in the script preparation code but not in the individual test cases. However, it's worth noting that this loop has been supported in modern browsers for a long time.Alternatives:
If you're looking to compare performance between these methods in your own tests, here are some alternatives:
Array.from(Map.prototype.values()).forEach
, you could use the native Map.forEach()
method directly on the Map object.
var map = new Map(); for (let i=0; i<100000; i++) { map.set(i, i); } map.forEach(function(value) { console.log(value); });
* For performance-critical code paths where the overhead of creating an iterator object is significant, consider using native methods like `Array.prototype.forEach()` or `Map.prototype.forEach()`.
* Example:
```
var arr = new Array(100000);
for (let i=0; i<arr.length; i++) {
arr[i] = i;
}
arr.forEach(function(value) {
console.log(value);
});