const mySet = new Set();
for (let i = 0; i < 10000; i++) {
mySet.add(`my_id_${i}`);
}
const [myFirstSetElement] = mySet;
console.log(myFirstSetElement);
const mySet = new Set();
for (let i = 0; i < 10000; i++) {
mySet.add(`my_id_${i}`);
}
const myFirstSetElement = mySet.values().next().value;
console.log(myFirstSetElement);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Destructuring assignment | |
Set iterator |
Test name | Executions per second |
---|---|
Destructuring assignment | 607.2 Ops/sec |
Set iterator | 598.9 Ops/sec |
This benchmark compares two ways to get the first element from a Set in JavaScript:
Option 1: Destructuring assignment
const mySet = new Set();
// ... populate the set ...
const [myFirstSetElement] = mySet;
console.log(myFirstSetElement);
This approach uses destructuring assignment to extract the first element from the Set. It's concise and considered a modern JavaScript idiom.
Option 2: Set iterator
const mySet = new Set();
// ... populate the set ...
const myFirstSetElement = mySet.values().next().value;
console.log(myFirstSetElement);
This approach uses the values()
method of the Set object to create an iterator, then calls next()
to get the first value and extract it using .value
. This is a more explicit way to access elements from an iterable.
Pros and Cons:
Destructuring Assignment:
Set Iterator:
Other Considerations:
The benchmark results show that destructuring assignment is faster in this specific case (Firefox 115). However, performance can vary depending on the JavaScript engine and other factors. In general, destructuring assignment is often the preferred approach for accessing elements from iterables due to its efficiency and readability.
Alternatives:
While not directly compared in this benchmark, there are other ways to access elements from a Set:
mySet.keys()
or mySet.entries()
: These methods return iterators over the keys or key-value pairs of the Set, respectively.Array.from(mySet)
creates an array containing all the elements of the Set.