Expand description
WeakMap, WeakSet, WeakRef and FinalizationRegistry.
§Why these are cheap here
The engine frees memory by reference counting with a cycle collector, so a box is
released the instant its last strong handle dies. [WeakGc] therefore already has the
two properties these classes need:
- it does not keep the target alive (it owns no strong reference), and
- it does not participate in cycle detection (
Trace for WeakGcvisits nothing), so aWeakMapwhose key is only reachable through the map does not keep the cycle alive.
That means a WeakMap entry disappears exactly when its key dies, with no second
“clear the dead entries” pass and no tracing-collector machinery: the map stores a
WeakGc per key, and looking a key up simply finds nothing once upgrade fails.
§What is not free: scheduling the cleanup callback
FinalizationRegistry’s cleanup callback must run “some time after” the target dies,
at a point when script is not running. Reference counting can notice a death precisely
(the strong count hits zero) but the crate gives no hook for it, and running script from
inside a Drop would be a re-entrancy hazard of the worst kind — the drop can happen
while a RefCell is borrowed, in the middle of arbitrary engine bookkeeping.
So the registry is drained at a safe point instead: drain_finalizers is called
from the microtask checkpoint, which is where a host may run script after a job anyway,
and it collects every registration whose target has expired by then. The observable
difference from a real GC is only when the callback fires — “at the next turn of the
event loop” rather than “at an unpredictable later moment” — which is within what
§9.10 permits and is what test262’s own $262.gc hook models.
§Why WeakMap uses WeakGc<JsObject> and not a symbol-keyed secret
A key must be an object, and two objects are one key exactly when they are the same
object. ptr_eq on a WeakGc answers that in one comparison, with no property written
onto the key — which matters, because a WeakMap must not add observable properties.
Functions§
- drain_
finalizers - Run every expired registration, across every registry on the realm.
- install
- Install the four globals.