javascript / expert
Snippet
Memory Management with WeakRef and FinalizationRegistry
WeakRef allows you to hold a weak reference to an object, meaning it doesn't prevent the object from being garbage collected. Combined with FinalizationRegistry, you can create sophisticated caches that automatically clean up metadata when the cached object is reclaimed by the engine.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
const cache = new Map();const registry = new FinalizationRegistry((key) => {console.log(`Cleaned up: ${key}`);});function createCachedRef(key, obj) {cache.set(key, new WeakRef(obj));registry.register(obj, key);}// Usage: const obj = cache.get(key)?.deref();
nodejs
Breakdown
1
new WeakRef(obj)
Creates a reference that does not prevent the object from being garbage collected.
2
new FinalizationRegistry((key) => { ... })
Defines a callback that triggers after an object registered with the registry is garbage collected.