var fooMap = new Map(); for(var i=0;i<10000;i++) { fooMap.set(i, i); } var other = [fooMap];
var fooMap = new Map(); for(var i=0;i<10000;i++) { fooMap.set(i, i); } var other = fooMap.keys();
var fooMap = new Map(); for(var i=0;i<10000;i++) { fooMap.set(i, i); } var other = fooMap.values();
var fooMap = new Map(); for(var i=0;i<10000;i++) { fooMap.set(i, i); } var other = [fooMap];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from | |
Map.keys | |
Map.values | |
Spread ... |
Test name | Executions per second |
---|---|
Array.from | 2272.7 Ops/sec |
Map.keys | 3541.3 Ops/sec |
Map.values | 3482.3 Ops/sec |
Spread ... | 2248.1 Ops/sec |
I'll break down the provided benchmark definition and test cases, explaining what's being tested, comparing options, and discussing pros and cons.
Benchmark Definition:
The benchmark is designed to compare the performance of four different approaches for creating an array from a Map:
Array.from()
Map.keys()
Map.values()
...
)Test Cases:
Each test case consists of two parts:
Here's a brief explanation of each test case:
Array.from()
: Creates an array from the values of the Map using Array.from()
with the spread operator (...
).Map.keys()
: Creates an iterator over the keys of the Map and then converts it to an array using the spread operator (...
).Map.values()
: Creates an iterator over the values of the Map and then converts it to an array using the spread operator (...
).Spread ...
: Directly spreads the values of the Map into a new array.Options Comparison:
The four approaches have different pros and cons:
Array.from()
: This approach is generally fast and efficient, especially when used with the spread operator (...
). However, it requires that the Map has numeric keys, which might not be the case for all Maps.Map.keys()
+ Spread ...: This approach uses an iterator to traverse the keys of the Map and then converts them to an array using the spread operator (...
). While this is a valid way to create an array from a Map, it can lead to slower performance due to the overhead of creating an iterator.Map.values()
+ Spread ...: Similar to Map.keys()
, but uses an iterator over the values instead. This approach also has the same trade-offs as using Map.keys()
plus spread (...
).Other Considerations:
Alternatives:
If you need to create an array from a Map and want alternative approaches:
for...of
loop: You can use a for...of
loop to iterate over the values of a Map and push them into a new array.Map.forEach()
+ spread (...
): Similar to using
Array.from()`, but uses a callback function to process each value before adding it to the new array.Object.entries()
: Instead of iterating over the keys or values of a Map, you can use Object.entries()
to get an array-like object with key-value pairs, and then convert it to a regular array using the spread operator (...
).Keep in mind that these alternatives might have different performance characteristics compared to the original approaches.