snippetjavascriptModeratepending
JavaScript WeakMap and WeakRef -- preventing memory leaks in caches
Viewed 0 times
WeakMapWeakRefFinalizationRegistrygarbage collectioncache eviction
browsernodejs
Problem
Caching objects with a regular Map keeps them in memory forever, preventing garbage collection even when nothing else references them.
Solution
Use WeakMap for metadata attached to objects (key is weakly held), and WeakRef + FinalizationRegistry for cache entries that auto-evict when the original object is garbage collected.
Code Snippets
WeakMap and WeakRef for memory-safe caching
// WeakMap: attach metadata without preventing GC
const metadata = new WeakMap();
function process(obj) {
if (!metadata.has(obj)) {
metadata.set(obj, { processed: Date.now() });
}
return metadata.get(obj);
}
// When obj is GC'd, metadata entry is automatically removed
// WeakRef: cache that allows GC
class WeakCache {
#cache = new Map();
#registry = new FinalizationRegistry(key => this.#cache.delete(key));
set(key, value) {
this.#cache.set(key, new WeakRef(value));
this.#registry.register(value, key);
}
get(key) {
const ref = this.#cache.get(key);
return ref?.deref(); // undefined if GC'd
}
}Revisions (0)
No revisions yet.