<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)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spreading | |
Set.forEach + Set.add | |
Generators | |
for loop |
Test name | Executions per second |
---|---|
Spreading | 332243.1 Ops/sec |
Set.forEach + Set.add | 339959.1 Ops/sec |
Generators | 283566.5 Ops/sec |
for loop | 325586.7 Ops/sec |
I'd be happy to help explain the provided benchmark.
Benchmark Overview
The benchmark measures different ways to union JavaScript Sets, which are collections of unique values. The test creates two sets, set1
and set2
, with random elements, and then compares four different methods for merging these sets:
Set.forEach
and Set.add
for
loopOptions Compared
Each option is compared to determine which one performs the best in terms of execution speed.
...
) to merge the sets. It's a concise and efficient way to create a new set with all elements from two existing sets.forEach
and adds it to another set using add
. While straightforward, this approach can be slower than spreading due to the overhead of iteration.function*() { yield* ... }
) allows for a more functional programming style. This method yields each element from one set, which is then added to another set. Generators can be an efficient way to process data in a streaming fashion.for
loop is used to iterate over elements and add them to the target set.Pros and Cons of Each Approach
Libraries and Special Features
The benchmark uses the nanoid
library, which is a simple and secure way to generate random IDs. This library is loaded via a script tag in the HTML preparation code.
There are no special JavaScript features or syntax used in this benchmark beyond what's standard in modern JavaScript (ES6+).
Alternatives
Other alternatives for merging sets could include:
Set.prototype.union()
or Set.prototype.intersection()
, if availableunionBy
functionfor...of
loops and conditional statementsKeep in mind that the choice of method depends on specific use cases, performance requirements, and personal preference.
I hope this explanation helps!