Testing different ways to compare Set equality

Benchmark created on


Description

5 different ways to compare sets to see if they are equal. Which is fastest?

Setup

// Test Set 1: 100 elements, identical (numbers 0-99)
const set1a = new Set(Array.from({ length: 100 }, (_, i) => i));
const set1b = new Set(Array.from({ length: 100 }, (_, i) => i));

// Test Set 2: 200 elements, identical with mixed types
const mixedArray = Array.from({ length: 200 }, (_, i) => i % 3 === 0 ? `str${i}` : i % 2 === 0 ? true : i);
const set2a = new Set(mixedArray);
const set2b = new Set(mixedArray);

// Test Set 3: 400 elements, identical (numbers 0-399)
const set3a = new Set(Array.from({ length: 400 }, (_, i) => i));
const set3b = new Set(Array.from({ length: 400 }, (_, i) => i));

// Test Set 4: 100 elements, non-identical (one extra element)
const set4a = new Set(Array.from({ length: 100 }, (_, i) => i));
const set4b = new Set(Array.from({ length: 99 }, (_, i) => i).concat(1000));

// Test Set 5: 200 elements, identical with objects
const objArray = Array.from({ length: 100 }, (_, i) => ({ id: i }));
const set5a = new Set([...objArray, ...Array.from({ length: 100 }, (_, i) => i)]);
const set5b = new Set([...objArray, ...Array.from({ length: 100 }, (_, i) => i)]);

// Array of all set pairs for looping
const allSets = [
  [set1a, set1b],
  [set2a, set2b],
  [set3a, set3b],
  [set4a, set4b],
  [set5a, set5b]
];

// Comparison Functions
function compareLoop(a, b) {
  if (a.size !== b.size) return false;
  for (const value of a) {
    if (!b.has(value)) return false;
  }
  return true;
}

function compareDiff(a, b) {
  if (a.size !== b.size) return false;
  return a.difference(b).size === 0;
}

function compareIntersect(a, b) {
  if (a.size !== b.size) return false;
  return a.intersection(b).size === a.size;
}

function compareSubset(a, b) {
  if (a.size !== b.size) return false;
  return a.isSubsetOf(b);
}

function compareArray(a, b) {
  if (a.size !== b.size) return false;
  const arrA = [...a].sort();
  const arrB = [...b].sort();
  return arrA.every((val, i) => val === arrB[i]);
}

Test runner

Ready to run.

Testing in
TestOps/sec
Loop with has()
for (let i = 0; i < allSets.length; i++) {
  compareLoop(allSets[i][0], allSets[i][1]);
}
ready
Difference-Based
for (let i = 0; i < allSets.length; i++) {
  compareDiff(allSets[i][0], allSets[i][1]);
}
ready
Intersection-Based
for (let i = 0; i < allSets.length; i++) {
  compareIntersect(allSets[i][0], allSets[i][1]);
}
ready
Subset-Based
for (let i = 0; i < allSets.length; i++) {
  compareSubset(allSets[i][0], allSets[i][1]);
}
ready
Array Conversion
for (let i = 0; i < allSets.length; i++) {
  compareArray(allSets[i][0], allSets[i][1]);
}
ready

Revisions

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