A memory profile can crash even when each iteration creates the same number of objects. The difference may be one reference that keeps those objects reachable longer. Data lifetime is the period during which an object remains reachable and usable before becoming eligible for reclamation. section 9.4.2 section 9.8
Tracing collectors begin at roots and follow references. Reachable objects stay alive; unreachable objects, including unreachable cycles, can be collected. Young objects are usually cheap: allocation is largely a pointer bump, and short-lived objects are reclaimed in the young generation. Objects that survive are promoted to the old generation, where tracing, copying, marking, sweeping, and promotion cost more. section 9.8
Manage lifetime by controlling reachability rather than merely reducing allocation:
- Capture only the values a closure needs; extracting userId before creating a callback prevents a multi-megabyte rawBody from surviving unnecessarily. section 9.4.2
- Treat awaits, timers, event listeners, and pending promises as lifetime extensions for captured scopes. section 9.8
- Distinguish pressure from a leak: stable memory that returns to baseline indicates pressure, while declining mu or a persistently elevated heap indicates a retained reference. section 11.2.2
A lifetime diagnostic
Run --trace-gc under realistic load. Stable Scavenges, heap size, and mu suggest healthy short lifetimes; escalating Mark-Compact pauses, heap growth, and declining mu indicate objects surviving longer than intended. section 9.8
