Course contentsShow
← JavaScript
Lesson 1897 of 2,72340. PerformanceFree lesson

Choosing the Right Data Structure

Discover how using Set/Map instead of Array for lookups can transform O(n) operations into O(1) operations.

Choosing the Right Data Structure

You'll learn: How picking Set or Map over Array can turn slow lookups from O(n) into instant O(1) operations.

The Performance Problem with Arrays

When you need to check if an item exists in an Array, JavaScript must scan through each element one by one until it finds a match (or reaches the end). This is O(n) — the time grows linearly with the array's size. With 1,000 items, you might check all 1,000.

Think of it like searching for a specific book by walking down every aisle in a library, shelf by shelf.

Enter Set and Map

Set and Map use hash-based storage, which is like having a magical index that tells you instantly which shelf holds your book — no walking required. Lookup becomes O(1), meaning it takes roughly the same time whether you have 10 items or 10,000.

When to use what:

  • Set: Check membership quickly (has() method)
  • Map: Store key-value pairs with fast key lookup (get() method)
  • Array: When you need order, indexing, or frequent iteration

Real-World Impact

// Slow: O(n) lookup
const ids = [101, 205, 387, /* ...thousands more */];
if (ids.includes(targetId)) { /* ... */ }

// Fast: O(1) lookup
const idSet = new Set([101, 205, 387, /* ...thousands more */]);
if (idSet.has(targetId)) { /* ... */ }

The bigger your collection, the more dramatic the speedup. This simple swap can eliminate performance bottlenecks in filtering, deduplication, and membership checks.

Key Takeaway: Always ask: "Will I be doing lookups?" If yes, consider Set or Map instead of Array to achieve constant-time performance instead of linear scanning.