Set Performance: Membership Tests at Scale
You'll learn: Why Set.has() dramatically outperforms Array.includes() when checking if an item exists in large collections.
The Performance Problem with Arrays
When you call array.includes(value), JavaScript must potentially check every single element in the array until it finds a match (or reaches the end). This is called O(n) time complexity—as your array grows, worst-case search time grows proportionally.
For small arrays, this isn't noticeable. But with thousands or millions of items? It becomes painfully slow.
How Sets Achieve O(1) Speed
Set uses a completely different internal structure (a hash table). When you call set.has(value), it calculates a "hash" of the value and jumps directly to where it should be—no scanning required. This is O(1) time complexity—constant time, regardless of size.
Think of it like this: An array is like searching a long bookshelf from left to right until you find your book. A Set is like having a magical catalog that tells you exactly which shelf and position to check instantly.
When It Matters
const largeArray = Array.from({ length: 100000 }, (_, i) => i);
const largeSet = new Set(largeArray);
// Slow: must scan up to 100,000 elements
largeArray.includes(99999); // O(n) - worst case scenario
// Fast: instant lookup
largeSet.has(99999); // O(1) - always fast
For a few dozen items, the difference is negligible. For thousands or millions, Set.has() can be hundreds of times faster than Array.includes().
Key Takeaway: Use Set and has() instead of Array and includes() when you need frequent membership checks on large collections—it transforms O(n) linear scans into O(1) instant lookups.