Expand description
quickjs-gc — reference counting with cycle collection.
QuickJS frees memory by reference counting and removes reference cycles with a
periodic collector (see JS_RunGC / JS_SetGCThreshold in the C API). Its
observable behaviour — an object is released as soon as the last reference
goes away, finalizers run at that moment, and cycles are reclaimed only when
the collector runs — is part of the semantics we have to reproduce, so we use
the same algorithm instead of a tracing GC.
This crate provides:
Heap— one per [Runtime]-equivalent; owns the registry of live boxes, the allocation accounting and the collector.Gc<T>— a strong, reference-counted handle. Cheap to clone, derefs toT, releases the value deterministically when the last handle dies.WeakGc<T>— a non-owning handle that does not keep the value alive and does not participate in cycle detection (used byWeakRef,WeakMapandFinalizationRegistry).Trace— implemented by every type that can ownGchandles, so the collector can walk the object graph.
§The collector
Heap::collect implements trial deletion (Bacon–Rajan “synchronous cycle
collection”):
- Every live box starts with
gc_refs = strong_count. - Every internal edge (a
Gcfield inside another box) decrements the child’sgc_refs. After this passgc_refs > 0means “at least one reference lives outside the heap”, i.e. the box is a root. - Mark everything reachable from the roots.
- Unmarked boxes are only reachable from garbage: their values are dropped (which releases the handles they hold) and the boxes themselves are freed once their strong count reaches zero.
§Contract
- A
Heapmust outlive everyGccreated from it. Dropping a heap with live boxes leaks them; it is not undefined behaviour. Trace::tracemust not mutate the object graph, allocate, or panic: it runs while the collector holds a snapshot of the heap.Gc<T>/WeakGc<T>are!Send + !Sync: a heap is single threaded, which matches a QuickJSJSRuntime(JS_SetSharedArrayBufferFunctionsis the only cross-thread escape hatch and it is handled injs-value).
Structs§
- Collect
Stats - Statistics returned by
Heap::collect. - Gc
- A strong, reference-counted handle to a heap value.
- Heap
- Owns the live-object registry for one JavaScript runtime.
- Tracer
- Visitor used by
Traceimplementations. - WeakGc
- A non-owning handle to a heap value.