Set unionizing

Benchmark created on


Setup

const N = 100000
const a1 = new Array(N).fill(1).map((v, i) => v + i)
const a2 = new Array(N).fill(N+1).map((v, i) => v + i)

const set1 = new Set(a1);
const set2 = new Set(a2);

function union(set, ...iterables) {
  const nextSet = new Set(set);

  for (const iterable of iterables) {
    for (const item of iterable) {
      nextSet.add(item);
    }
  }

  return nextSet;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Set.union()
const newSet = set1.union(set2)
ready
Constructor + forEach
const newSet = new Set(set1)
set2.forEach((s) => newSet.add(s))
ready
Constructor plus loop
const newSet = new Set(set1)
for (const s of set2) {
  newSet.add(s)
}
ready
Util
const newSet = union(set2, set2)
ready
Generator
const set3 = new Set(function*() { yield* set1; yield* set2;}());
ready
Spread
const set3 = new Set([...set1, ...set2])
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.