Memory management is critical at Google scale. WeakMap and WeakRef are essential tools for avoiding memory leaks in long-running applications.
WeakMap vs Map
| Feature | Map | WeakMap |
|---|---|---|
| Key types | Any | Objects only |
| Enumerable | Yes (.keys(), .values()) | No |
| GC behavior | Keys prevent GC | Keys are weakly held |
| Size property | Yes | No |
Use Case: Private Data
const privateData = new WeakMap();
class User {
constructor(name, ssn) {
this.name = name;
privateData.set(this, { ssn });
}
getSSN() {
return privateData.get(this).ssn;
}
}
// When User instance is GC'd, private data is tooUse Case: DOM Metadata
const elementData = new WeakMap();
function trackElement(el) {
elementData.set(el, {
clickCount: 0,
firstSeen: Date.now()
});
}
// When element is removed from DOM and GC'd,
// metadata is automatically cleaned upWeakRef and FinalizationRegistry
WeakRef holds a weak reference to an object. FinalizationRegistry lets you run cleanup when an object is garbage collected.
const cache = new Map();
const registry = new FinalizationRegistry((key) => {
cache.delete(key);
});
function cacheResult(key, value) {
const ref = new WeakRef(value);
cache.set(key, ref);
registry.register(value, key);
}
function getCached(key) {
const ref = cache.get(key);
return ref?.deref(); // Returns undefined if GC'd
}Production Warning
WeakRef and FinalizationRegistry are non-deterministic — you can't predict when GC runs. Never use them for critical logic. They're optimization tools, not correctness tools.