var arr = [];
for (var i = 0; i < 10000; i++) {
arr.push(Math.floor(Math.random() * 1000));
}
const ss = new Set(arr)
arr = [ss]
arr = Array.from(new Set(arr))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
spread | |
Array.from |
Test name | Executions per second |
---|---|
spread | 19432.3 Ops/sec |
Array.from | 20791.0 Ops/sec |
Let's break down what's being tested in this benchmark and explain the options, pros, cons, and considerations.
Benchmark Overview
The benchmark is designed to compare two approaches: using the spread operator (...
) to convert a Set to an array, versus using Array.from()
with a Set as its argument.
Script Preparation Code
The script preparation code creates an empty array arr
and populates it with 10,000 random integers between 0 and 1000 using a for
loop. This initializes the input data for both test cases.
Html Preparation Code
There is no HTML preparation code provided, which means that the benchmark focuses solely on JavaScript execution performance.
Individual Test Cases
The two test cases are:
...
) to convert a Set created from arr
back into an array.const ss = new Set(arr);
arr = [...ss];
Array.from()
with a Set as its argument to convert arr
into an array.Library Usage
Both test cases use the built-in JavaScript Set
and Array.prototype.push()
methods, which are part of the ECMAScript standard (ES6).
Special JavaScript Features/Syntax
There is no special JavaScript feature or syntax being tested in this benchmark. The focus is solely on comparing two basic array conversion approaches.
Pros and Cons of Each Approach
Array.from()
.Array.from()
with a Set as its argument has some advantages:Considerations
When deciding between these two approaches, consider the following factors:
Array.from()
might be a better choice. Otherwise, the spread operator might be sufficient.Other Alternatives
In addition to these two approaches, there are other ways to convert an array to a Set or vice versa:
Set.from()
(ECMAScript 2022): This method creates a new Set from an iterable object.Object.keys()
and then creating a Set: You can use Object.keys()
to get an array of key names from an object (which is essentially equivalent to an array) and then create a Set from that array.These alternatives might be relevant in specific scenarios, but they are not directly comparable to the spread operator and Array.from()
approaches used in this benchmark.