⚡ Fix a Map Used as a Cache Growing Forever Because Object Keys Inserted Into It Are Compared by Reference, So Two Structurally Identical Keys Never Collide
A Map lets you use objects as keys, unlike a plain object which coerces every key to a string, which looks like exactly what you want for caching by some data shape. But Map key equality is SameValueZero, which for objects means reference identity, not structural equality — two separately created object instances with exactly the same properties and values are two distinct keys as far as a Map is concerned. A cache that builds a fresh lookup object on every call and uses it as a Map key never produces a hit, because every call constructs a brand-new object reference, so the Map just keeps accumulating entries that are each permanently unique, growing without bound while never actually deduplicating anything.
🔎 The Problem
const cache = new Map();
function getCached(userId, scope) {
const key = { userId, scope }; // new object reference every call
if (cache.has(key)) return cache.get(key);
const value = computeExpensiveResult(userId, scope);
cache.set(key, value);
return value;
}
getCached(1, "reports"); // cache.size === 1
getCached(1, "reports"); // identical-looking key, but a DIFFERENT reference
// cache.has(key) is false - cache.size === 2
✅ Fix: Key by Value, Not by a Freshly Built Reference
- Derive a stable primitive key — a string built from the relevant fields, like `${userId}:${scope}` — and use that as the Map key instead of an object literal, since primitive keys compare by value the way a cache lookup actually needs.
- If the key genuinely needs to be a specific object for identity-based caching, reuse the same object reference across calls rather than constructing a new one each time, which usually means caching the object itself somewhere stable instead of rebuilding it inline.
- Switch to a WeakMap when the key really is meant to be a long-lived object you want garbage-collected automatically, or add a periodic size check, so a mismatch like this at least bounds memory growth instead of letting it run unbounded.
🚨 Why This Is Dangerous
- An ever-growing Map backing a “cache” that never actually caches anything is a slow memory leak that looks, from the outside, like the opposite of its real symptom — a feature billed as a performance optimization that’s silently consuming more memory with every call it was supposed to speed up.
A Map lets an object be a key, but it never promised two objects that merely look alike would count as the same one.
