javascript / expert
Snippet
Advanced Memory Management with WeakRef and FinalizationRegistry
WeakRef and FinalizationRegistry allow for advanced memory management in long-running applications. A WeakRef lets you hold a reference to an object without preventing its garbage collection, while FinalizationRegistry provides a callback when an object is actually reclaimed. This is crucial for implementing caches that don't leak memory or managing external resources tied to JavaScript objects.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
const registry = new FinalizationRegistry((heldValue) => {console.log(`Resource ${heldValue} was garbage collected`);});function createHeavyObject(id) {const obj = { id, data: new BigUint64Array(1000000) };const ref = new WeakRef(obj);registry.register(obj, id);return ref;}let heavyRef = createHeavyObject('session_123');// Access via heavyRef.deref()
nextjs
Breakdown
1
const registry = new FinalizationRegistry((heldValue) => { ... });
Creates a registry that triggers a callback after registered objects are garbage collected.
2
const ref = new WeakRef(obj);
Creates a weak reference; the object can be reclaimed even if this reference exists.
3
registry.register(obj, id);
Registers the object with the registry to track its lifecycle using the provided ID.