var mySet = new Set()
for (let i = 0; i < 999; i += 1) {
mySet.add(i)
}
const myArr = [mySet]
const myArr = Array.from(mySet)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
spread | |
concat |
Test name | Executions per second |
---|---|
spread | 95007.0 Ops/sec |
concat | 116118.4 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
What is being tested?
The benchmark measures the performance of creating an array from a Set object using two different methods: Array.from()
and array spread (...
operator).
Options compared
There are two options being compared:
Array.from(mySet)
: This method creates a new array by calling the from()
function on the Set object, passing it as an argument.myArr = [...mySet]
: This is the spread operator syntax, which creates a new array by copying all elements from the Set object into a new array.Pros and cons of each approach
Array.from(mySet)
:map()
, filter()
).myArr = [...mySet]
:from()
function call.Array.from()
. The spread operator can also lead to unexpected behavior if not used carefully.Library and purpose
The Set
object is a built-in JavaScript library that provides a collection of unique values. It's implemented as an instance of the Map
class, which means it uses a hash table to store its elements.
In this benchmark, the Set object is created using the Script Preparation Code
, and then used to create arrays using both methods.
Special JS feature or syntax
There isn't any special JavaScript feature or syntax being tested in this benchmark. However, it's worth noting that the spread operator (...
) has been a part of ECMAScript since ES6 (2015), while Array.from()
was introduced in ES2019 (2017).
Other alternatives
In theory, other methods could be used to create arrays from Sets, such as:
myArr = mySetToArray(mySet)
: A custom function that converts a Set to an array.myArr = [...new Set(...)]
: This method creates a new Set from the spread operator and then converts it to an array.However, these alternatives are not tested in this benchmark, and the results might vary depending on the implementation and optimizations used by the browser or JavaScript engine.
Overall, this benchmark provides a simple yet insightful comparison of two common ways to create arrays from Sets in JavaScript.