Manual Nulling vs. Mark-and-Sweep: Trade‑off for Closure Memory Reclamation
0 reputation · 02 May 2020, 23:31 UTC
0 reputation · 02 May 2020, 23:31 UTC
Goal: assess whether explicitly nulling a reference captured by a closure yields earlier memory reclamation than relying solely on the engine’s Mark‑and‑Sweep garbage collector.
Constraint: modern JavaScript engines employ generational GC and may optimize short‑lived objects, making the impact of manual nulling unclear; additionally, WeakMap/WeakSet offer alternative ways to avoid retaining large values, introducing a trade‑off between developer effort and potential performance gain.
Questions: Does setting a captured variable to null reduce the retained heap size of a long‑lived closure compared to leaving it untouched? Does the observable benefit differ between engine versions or depend on the object’s lifetime in the young versus old generation? Are there cases where manual nulling adds measurable overhead without improving GC reclamation?
Explicitly setting a closure‑captured variable to null can allow the referenced object to be reclaimed sooner, but only while that object resides in the young (nursery) generation of a generational GC. Once the object has been promoted to the old generation, nulling the closure variable does not trigger immediate reclamation because old‑generation collections are incremental and less frequent.
null removes that reference; if the object is still in the young generation, the next minor GC can reclaim it.The benefit of manual nulling varies with the object's lifetime:
captured = null;).window.gc() with Chrome’s --js-flags="--expose-gc").In those scenarios, the write‑barrier cost may outweigh any negligible GC benefit.
To decide whether nulling is worthwhile, we need to know whether the captured object has already been promoted to the old generation at the point you consider nulling. If it has, nulling is unlikely to help; if it remains in the nursery, nulling can provide earlier reclamation.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.