Sub topic 11
Building a Weak-Value Cache
This chapter assumes you already know how WeakRef and deref() work, how FinalizationRegistry passes a held value to its callback, and how Map works. Here those pieces are combined into one common pattern: a cache that does not keep its values alive.
Why WeakMap Is Not Enough
A WeakMap holds its keys weakly. That is a good fit when you want to attach data to an object you don't own. Many caches work the other way round. The key is a string or number, such as a URL, a user ID, or a file path, and the value is a large object that is expensive to compute. A WeakMap cannot use primitive keys, and its values are held strongly in any case.
The structure you need is a weak-value cache:
- A plain
Mapfrom key toWeakRef(value), so the cache never keeps a value alive by itself. - A
FinalizationRegistrythat deletes the map entry after its value is collected, so deadWeakRefwrappers do not pile up.
The Implementation
const cache = new Map();
const registry = new FinalizationRegistry((key) => {
const ref = cache.get(key);
if (ref !== undefined && ref.deref() === undefined) {
cache.delete(key);
}
});
function getCached(key, compute) {
const cached = cache.get(key)?.deref();
if (cached !== undefined) return cached;
const value = compute(key);
cache.set(key, new WeakRef(value));
registry.register(value, key);
return value;
}
// Example use
const report = getCached('q3', (k) => ({ id: k, rows: new Array(1e5).fill(0) }));
console.log(report.id); // 'q3'
console.log(getCached('q3', () => { throw new Error('not called'); }) === report); // truegetCached treats an entry as missing in two cases: no entry exists, or the entry's WeakRef has been cleared. Either way it computes a fresh value, stores a new WeakRef, and registers the value with the key as the held value. The key is a primitive, so using it as the held value does not keep the value alive.
The Stale-Entry Check
The callback does not simply call cache.delete(key). Consider this sequence:
- The value for
'q3'becomes unreachable and is collected. - Before the cleanup callback runs,
getCached('q3', ...)sees a clearedWeakRefand stores a new value under'q3'. - The callback for the old value now runs with
'q3'.
An unconditional delete at step 3 would remove the fresh entry. Checking ref.deref() === undefined makes sure the callback deletes only an entry whose value is actually gone.
Common Errors
| Mistake | Consequence |
|---|---|
| Storing `value` directly in the `Map` | The cache keeps every value alive, so it is just an ordinary cache |
| Using `value` as the held value | `register()` throws a `TypeError` |
| Deleting without the stale check | Fresh entries get removed when a key is reused |
| Relying on the callback for correctness | The callback may run late or never, so `getCached` has to check `deref()` itself |
Exercise
Suppose you remove the FinalizationRegistry and keep only the Map of WeakRefs. Does getCached still return correct results? What problem remains?
Show answer
Yes. getCached still returns correct results because it checks deref() and recomputes when the WeakRef is empty. The remaining problem is a memory leak: each key keeps an empty WeakRef wrapper in the Map forever, so the Map grows without limit as new keys arrive.
Exercise
Why is it safe to use the key as the held value, but not a wrapper object that contains the value?
Show answer
The registry holds the held value strongly. A primitive key does not reference the cached value. A wrapper that contains the value would keep the value reachable, so the value could never be collected and the callback would never run.