const array = Array.from({length: 10_000}, () => Math.floor(Math.random() * 10_000_000));
const map = new Map();
array.forEach((x, i) => map.set(x, i));
return new Map(map);
return new Map([map])
const newMap = new Map();
map.keys().forEach(x => newMap.set(x, map.get(x)));
return newMap
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
From map | |
From array | |
Step-by-step |
Test name | Executions per second |
---|---|
From map | 1514.0 Ops/sec |
From array | 1113.0 Ops/sec |
Step-by-step | 1241.9 Ops/sec |
The benchmark titled "Map copying" is designed to evaluate different methods of copying a Map
object in JavaScript. The benchmark executes three distinct approaches to creating a new Map
initialized with the entries of an existing one.
From map:
return new Map(map);
Map
constructor, which accepts an existing Map
instance to create a new copy of it.From array:
return new Map([...map])
Map
into an array using the spread operator (...
) and then passes that array to the Map
constructor to create a new Map
.Step-by-step:
const newMap = new Map();
map.keys().forEach(x => newMap.set(x, map.get(x)));
return newMap;
Map
, retrieves the corresponding value, and sets it in a new Map
one-by-one.The benchmark measures the performance by computing the number of executions per second for each method. The results are as follows:
From map:
Map
.Step-by-step:
From map
approach, likely due to the overhead of repeatedly accessing the original Map
and inserting entries individually.From array:
From map (Direct Constructor):
Map
.From array (Spread Operator):
Map
constructor with an existing Map
.Step-by-step (Iterative Approach):
get
and set
).Map
is used in the application. If performance is critical and frequent copying is required, the From map
method is recommended.From map
) is optimal, readability might favor the other methods in contexts where performance is not a bottleneck.Map
, but that could result in data structure transformation losses and is often less efficient.These performance insights can help developers choose the most suitable method for copying Map
instances depending on their specific application's requirements and performance needs.