capypad
0 day streak
javascript / expert
Snippet

Memory-Efficient Caching with WeakRef

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 caches that automatically clean up when memory is low without keeping objects alive indefinitely.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const cache = new Map();
const registry = new FinalizationRegistry(key => {
const ref = cache.get(key);
if (ref && !ref.deref()) cache.delete(key);
});
 
function getCachedData(key, factory) {
const ref = cache.get(key);
let data = ref?.deref();
if (!data) {
data = factory();
cache.set(key, new WeakRef(data));
registry.register(data, key);
}
return data;
}
Breakdown
1
new WeakRef(data)
Creates a reference that doesn't count towards reachability for the garbage collector.
2
ref?.deref()
Attempts to access the object; returns undefined if it has already been collected.
3
new FinalizationRegistry(...)
Sets up a callback that triggers after an object registered with it is garbage collected.