var fooMap = new Map();
for(var i=0;i<100;i++) {
fooMap.set(i, {n: i});
}
var other = Array.from(fooMap.values());
var fooMap = new Map();
for(var i=0;i<100;i++) {
fooMap.set(i, {n: i});
}
var other = [fooMap.values()];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from | |
Spread |
Test name | Executions per second |
---|---|
Array.from | 263112.0 Ops/sec |
Spread | 276573.3 Ops/sec |
The provided benchmark measures the performance difference between two approaches: using the Map
data structure in JavaScript and converting it to an array using either the spread operator ([...]
) or the Array.from()
method.
Options compared:
[...]
): This approach converts a map (or any other iterable) to an array by creating a new array with all the values from the map.Array.from()
Method: This approach also converts a map to an array, but uses the Array.from()
method to create a new array with all the values from the map.Pros and Cons of each approach:
[...]
):Array.from()
Method:Array.from(map, obj => obj.n)
).Other considerations:
Array.from()
method can also be used with other iterables, making it more versatile than the spread operator.Library and syntax:
In this benchmark, no libraries are explicitly mentioned, but the use of the Map
data structure suggests that the JavaScript standard library is being tested. No special JavaScript features or syntax are mentioned.
Other alternatives:
For creating arrays from maps, other approaches could include:
reduce()
method to create an array.mapValues()
function.However, the spread operator and Array.from()
method are likely the most common and efficient ways to perform this operation in JavaScript.