var map = new Map()
for (let i = 0; i< 100; i++) {
map.set(Math.random().toString(), Math.random())
}
Array.from(map.values())
new Array(map.values())
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
From | |
New |
Test name | Executions per second |
---|---|
From | 1103123.1 Ops/sec |
New | 1044006.6 Ops/sec |
Let's break down what's being tested in this JavaScript microbenchmark.
Benchmark Overview
The benchmark measures the performance difference between two approaches to convert a Map object into an array:
Array.from()
: Specifically, Array.from(map.values())
...
): new Array(...map.values())
Comparison of Approaches
Array.from()
approachPros:
Cons:
...
) approachPros:
Array.from()
Cons:
Array.from()
Library Usage
None of the test cases use any external libraries. The benchmark only relies on built-in JavaScript features.
Special JS Features/Syntax
The test case uses the spread operator (...
) and Array.from()
methods, both of which are standard JavaScript features since ES6. No other special features or syntax are used in this benchmark.
Other Alternatives
If you need to convert a Map object into an array, there are other approaches besides these two:
for...in
loop: var arr = []; for (var key in map) arr.push(map.get(key))
Object.values()
method (introduced in ES6): Array.from(Object.values(map))
However, the spread operator (...
) and Array.from()
approaches are generally considered the most concise and efficient ways to achieve this conversion.
I hope this explanation helps!