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
Use Case: DOM Metadata
WeakRef and FinalizationRegistry
WeakRef holds a weak reference to an object. FinalizationRegistry lets you run cleanup when an object is garbage collected.
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.