var map = new Map();
map.set("hello", "world");
map.set("done", "do");
const array = Array.from(map.values());
var map = new Map();
map.set("hello", "world");
map.set("done", "do");
const array = [map.values()]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array.from | |
spread syntax |
Test name | Executions per second |
---|---|
array.from | 1733401.0 Ops/sec |
spread syntax | 2875558.0 Ops/sec |
Let's dive into the details of this benchmark.
What is being tested?
The benchmark is comparing two ways to create an array from the values of a Map
object in JavaScript:
Array.from()
method (array.from
)[...map.values()]
)What are the options compared?
Two different methods are being compared:
Array.from()
: This is a built-in JavaScript method that creates an array from an iterable (such as a Map
object). It takes one argument: the iterable to create the array from.[...map.values()]
): This is a shorthand way to create an array from an iterable using the spread operator. The values()
method of the Map
object returns an iterator over its values, which are then "spread" into an array.Pros and Cons
Here's a brief summary of each approach:
Array.from()
: This method is concise, efficient, and widely supported across browsers and environments. It's also easy to read and understand.Array.from()
method[...map.values()]
): This approach uses a more modern JavaScript feature (spread operator) and is still relatively efficient. However, it may be less familiar to developers without experience with spread syntax.Array.from()
Other considerations
When choosing between these two approaches, consider the following:
Array.from()
might be more efficient and concise.[...map.values()]
) can make your code more readable.Library and special JS feature
In this benchmark, there is no external library used. However, it does involve a modern JavaScript feature: the spread operator ([...]
).
The Map
object is a built-in JavaScript data structure that stores key-value pairs in a way similar to objects, but with some differences (e.g., keys can be any type of value). The values()
method returns an iterator over its values.
Alternatives
If you need to create arrays from iterables and don't care about the performance difference between these two approaches, you could use other methods:
for...of
loop: This approach is less concise than Array.from()
or spread syntax but can be used in some situations where those methods are not available.const array = []; for (let value of map.values()) { array.push(value); }
reduce()
method: This approach involves creating a new array by reducing an iterable to a single value. While not directly related to creating arrays from iterables, it can be used in some cases where you need to process the values before storing them in an array.const array = map.values().reduce((acc, value) => acc.push(value), []);
Keep in mind that these alternatives might have their own performance implications and readability trade-offs.