const map = new Map()
for(let i = 0; i < 10000; i++){
map.set(i,i)
}
const arr = Array.from(map.values())
const map = new Map()
for(let i = 0; i < 10000; i++){
map.set(i,i)
}
const arr = [map.values()]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from | |
spread |
Test name | Executions per second |
---|---|
Array.from | 1907.3 Ops/sec |
spread | 1960.9 Ops/sec |
Let's dive into the Benchmark Definition and test cases.
Benchmark Purpose
The benchmark measures the performance of two ways to convert a Map object's values to an array:
Array.from(map.values())
[...map.values()]
)These approaches are being compared because they have different performance characteristics. The spread operator is more modern and concise, but it may be slower due to its syntax sugar.
Options Compared
The two options are being compared in terms of their execution time. The goal is to determine which approach is faster and more efficient for large datasets like the one used in this benchmark (10,000 iterations).
Pros and Cons of Each Approach
Array.from(map.values())
[...map.values()]
)Array.from()
.Library Used
In this benchmark, no libraries are explicitly mentioned. However, it's worth noting that the Map
object is a built-in JavaScript API, so no external library is required to use it.
Special JS Features or Syntax
The benchmark uses two modern features:
[...]
): A syntax sugar introduced in ECMAScript 2015 (ES6) for creating arrays from iterables.=>
): Used in the for...of
loop to define a concise and readable loop body.Benchmark Preparation Code
The benchmark preparation code is provided as a string, which is executed before running each test case:
const map = new Map()
for (let i = 0; i < 10000; i++) {
map.set(i, i)
}
This code creates a Map
object with 10,000 key-value pairs and sets the value of each key to its corresponding index.
Other Alternatives
If you wanted to compare other approaches for converting a Map object's values to an array, some alternatives could be:
forEach()
method: map.forEach((value) => { arr.push(value); })
reduce()
method: arr = map.values().reduce((acc, value) => acc.concat([value]), [])
for
and push()
: const arr = []; for (let i = 0; i < 10000; i++) { arr.push(map.get(i)); }
Keep in mind that these alternatives may have different performance characteristics compared to the spread operator or Array.from()
.
In conclusion, this benchmark aims to determine which approach is faster and more efficient for converting a Map object's values to an array. The spread operator and Array.from()
are two modern approaches with different pros and cons, while traditional loops and older browsers may require alternative solutions.