<script src="https://cdnjs.cloudflare.com/ajax/libs/nanoid/4.0.1/index.browser.js" integrity="sha512-YFaQHp+hWX9CMeIMngYK23kSIWaYlgsswmzmIdEw/HcK/5NLhXY2MbT0wQB5DnUzjW1uky4quIHtksukqZGkMw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
const SET_SIZE = 3000;
var set1 = new Set()
var set2 = new Set()
while (i < SET_SIZE) {
const nid = 'key:'+Math.random();
set1.add(nid);
if (i % 2 == 0) set2.add(nid);
i++;
}
while (i < SET_SIZE / 2) {
set2.add('key:'+Math.random());
}
const set3 = new Set([set1, set2]);
console.log(set3.size)
const set3 = new Set(set1);
set2.forEach(el => set3.add(el));
console.log(set3.size)
const set3 = new Set(function*() { yield* set1; yield* set2; }());
console.log(set3.size)
const set3 = new Set(set1);
for(let el of set2) set3.add(el)
console.log(set3.size)
console.log(set1.union(set2).size)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spreading | |
Set.forEach + Set.add | |
Generators | |
for loop | |
builtin union |
Test name | Executions per second |
---|---|
Spreading | 459560.8 Ops/sec |
Set.forEach + Set.add | 466256.5 Ops/sec |
Generators | 406054.9 Ops/sec |
for loop | 445394.8 Ops/sec |
builtin union | 453611.9 Ops/sec |
The benchmark on MeasureThat.net titled "Set union methods even more with builtin" evaluates different methods for combining two JavaScript Sets. Sets are a built-in JavaScript object that allows the storage of unique values, making them useful for operations like unions. The benchmark presents various ways to achieve the union of two sets (set1
and set2
), which have been initialized with specific values in the preparation code.
Spreading
const set3 = new Set([...set1, ...set2]);
...
) to expand the elements of both sets into a new Set.Set.forEach + Set.add
const set3 = new Set(set1); set2.forEach(el => set3.add(el));
set1
, and then elements from set2
are added one by one using forEach
.Generators
const set3 = new Set(function*() { yield* set1; yield* set2; }());
for loop
const set3 = new Set(set1); for(let el of set2) set3.add(el)
for...of
loop is used to iterate through set2
and add elements to a new Set initialized with set1
.builtin union
console.log(set1.union(set2).size)
The results show the performance (in executions per second) of each method as tested under a specific environment (Chrome 134 on macOS). The Set.forEach + Set.add
method was the fastest, followed closely by the spread operator. The built-in union method, although hypothetical, performed well among the available tests, while the generator method was the slowest.
As with any programming task, alternatives also exist:
Each of these approaches has its trade-offs in terms of complexity, readability, performance, and compatibility. When choosing a method for union operations, developers should consider the size of their data, the importance of code clarity, and whether performance is a critical factor in their specific context.