Course contentsShow
← Web Development
Lesson 2114 of 2,98238. JavaScript Performance in the BrowserFree lesson

Cache Structures That Grow Indefinitely

Identify memory leaks from caches, Maps, and Sets that accumulate data without size limits or expiration.

Cache Structures That Grow Indefinitely

You'll learn how unmanaged cache structures like Maps, Sets, and plain objects can silently consume memory until your application grinds to a halt.

The Problem

A cache is meant to speed up repeat operations by storing results in memory. But unlike the browser's built-in garbage collector—which cleans up unreachable objects—caches you create don't clean themselves. Every time you add an entry to a Map, Set, or object used as a cache, that data stays in memory forever unless you explicitly remove it.

Think of it like a warehouse where you keep storing boxes but never throw any away. Eventually, you run out of space.

Common Culprits

// DANGER: This cache grows forever
const apiCache = new Map();

function fetchData(url) {
  if (apiCache.has(url)) {
    return apiCache.get(url);
  }
  
  const result = fetch(url).then(r => r.json());
  apiCache.set(url, result); // Never removed!
  return result;
}

Every unique URL gets cached permanently. Visit 10,000 different pages? You now have 10,000 cached entries eating memory.

The same issue occurs with:

  • Set collections tracking "seen" items
  • Plain objects used as lookup tables
  • WeakMap misuse (storing primitive keys defeats its purpose)

The Solution Mindset

You need size limits or expiration policies:

  • Cap entries (e.g., keep only the last 100)
  • Time-based expiration (remove entries older than 5 minutes)
  • LRU (Least Recently Used) eviction

Without these safeguards, your cache becomes a memory leak in disguise.

Key Takeaway: Caches, Maps, and Sets won't clean themselves—implement size limits or expiration logic, or watch your memory usage balloon indefinitely.