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 map.values().toArray();
return Array.from(map.values());
return [map.values()];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map.values().toArray() | |
Array.from(Map.values()) | |
[...Map.values()] |
Test name | Executions per second |
---|---|
Map.values().toArray() | 1398.0 Ops/sec |
Array.from(Map.values()) | 11651.2 Ops/sec |
[...Map.values()] | 11621.5 Ops/sec |
The benchmark tests three different methods for converting the values of a Map
object to an array in JavaScript. The objective is to compare their performance, particularly focusing on execution speed, as measured in executions per second. Here’s a detailed breakdown of the comparison:
Map.values().toArray()
toArray()
function directly on the iterator returned by Map.values()
. However, toArray()
is not a native method in the JavaScript language for iterators.toArray()
method existed, allowing for method chaining.toArray()
does not exist on the Map.values()
iterator, this will likely result in a runtime error. Therefore, this option effectively tests the invalidity of using a non-existent method.Array.from(Map.values())
Array.from()
static method, which creates a new array from an iterable (in this case, the values of a Map
).Map.values()
iterator) into an array.[...Map.values()]
...
) to expand the iterable returned by Map.values()
into an array.Array.from()
for transformations, though in many cases where no transformation is needed, it’s very efficient.From the benchmark results, we can see the following performance measurements (in executions per second):
Array.from(Map.values())
: ~39,053[...Map.values()]
: ~38,988Map.values().toArray()
: ~6,268 (likely not representative due to the incorrect assumption about a non-existent method).Array.from()
and the spread syntax, which showcase similar performance metrics, with a slight edge going to Array.from()
.Map.values().toArray()
test serves as a cautionary example, affirming that invalid method calls can lead to performance measurements that fail to represent a valid use case in a project.Map
values to an array include:forEach
): Can be used when additional processing is required during the conversion.map()
on the iterator: This would need to first convert the values to an array using one of the valid methods above before applying map()
.When deciding which method to use, developers should balance performance with code readability and maintainability, along with the specific context of the application.