🗑️ Know When Objects Are Garbage Collected
WeakMap is known. WeakRef and FinalizationRegistry give advanced memory management. Cache cleanup, resource release, memory leak detection.
📝 WeakRef Example
let obj = { data: 'important' };
const weakRef = new WeakRef(obj);
// Later, obj might be garbage collected
obj = null;
// Check if still alive
const revived = weakRef.deref();
if (revived) {
console.log('Object still exists:', revived);
} else {
console.log('Object was garbage collected');
}
🎯 FinalizationRegistry (Cleanup)
const registry = new FinalizationRegistry((heldValue) => {
console.log(`Object with ${heldValue} was garbage collected`);
// Close file handles, release external resources
});
let resource = { id: 1, data: 'expensive' };
registry.register(resource, resource.id);
// Later, when resource is no longer referenced
resource = null;
// GC will call the callback with '1'
// Unregister if still needed
registry.unregister(resource);
đź’ˇ Use Cases
- Memory-constrained environments (mobile, embedded)
- Cache with automatic cleanup (weak cache)
- Debugging memory leaks (log when objects die)
- Integration with C++ via WebAssembly (manual memory)
“Cache grew to 500MB. WeakRef let cache auto-clean when memory pressure hits. No more OOM crashes. FinalizationRegistry logs what was removed. Powerful but careful!”
