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).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.9 Ops/sec |
Array.prototype.forEach | 4.4 Ops/sec |
Array.from(Map.prototype.values()).forEach | 3.7 Ops/sec |
Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The benchmark in question compares the performance of Map.forEach
, Array.forEach
, and Array.from(Map.prototype.values()).forEach
methods.
What's being tested?
The benchmark tests the execution time of three different approaches:
forEach
method.forEach
method.Array.from
and then iterates over it using forEach
.Options comparison
The three methods have different approaches to iteration:
Array.from
and then iterates over it using forEach
. This approach involves two steps, which may impact performance.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Library and Special JavaScript Features
The benchmark uses the following libraries:
Array.from
is a standard JavaScript method that creates an array from an iterable.Other Considerations
console.log
as a logging function can impact performance since it may involve additional overheads like printing to the console.Alternatives
If you're interested in exploring alternative approaches or testing other methods, here are some options:
forEach
, you can use a for-in loop to iterate over the Map object's values. However, this method may not be as straightforward and could lead to unexpected behavior if you're not careful.map()
. You can use this approach alongside forEach
for a more comprehensive comparison.for...of
, reduce()
, or filter()
for an alternative perspective.