I want to understand What are WeakRef
and finalizers in ES2021 with a real simple example and Where to use them.
I know, WeakRef
is a class. This will allow developers to create weak references to objects, while a finalizer or FinalizationRegistry
allows you to register callback functions that will be invoked when an object is garbage collected
const myWeakRef = new WeakRef({
name: 'Cache',
size: 'unlimited'
})
// Log the value of "myWeakRef":
console.log(myWeakRef.deref())
As always, MDN's docs help.
In almost every other part of JS, if some object (A) holds a reference to another object (B), B will not be garbage-collected until A can be fully garbage-collected as well. For example:
In this situation, the
theB
will never be garbage collected (unlesstheA.obj
gets reassigned) becausetheA
on the top level contains a property that holds a reference totheB
; it's a strong reference, which prevents garbage collection.A WeakRef, on the other hand, provides a wrapper with access to an object while not preventing garbage collection of that object. Calling
deref()
on the WeakRef will return you the object if it hasn't been garbage collected yet. If it has been GC'd,.deref()
will returnundefined
.FinalizationRegistry deals with a similar issue:
You first define the registry with the callback you want to run, and then you call
.register
on the registry with the object you want to observe. This will let you know exactly when something gets garbage collected. For example, the following will logJust got GCd!
once theobj
gets reclaimed:You can also pass a value when calling
.register
that gets passed to the callback when the object gets collected.will log
the object named "obj"
it gets GC'd.All this said, there is rarely a need for these tools. As MDN says:
Best to let the engine itself deal with garbage collection automatically whenever possible, unless you have a really good reason to care about it yourself.