liveBook · Manning

Head retention

As explained in Clojure: The Essential Reference

Head retention is the unintended preservation of references to the beginning of a lazy sequence, which can keep realized elements in memory and prevent garbage collection.

Head retention is the unintended preservation of references to the beginning of a lazy sequence. As elements are realized, retaining that head can keep earlier elements in memory and prevent garbage collection, undermining lazy processing of large inputs. section 3.4.5

Realizing versus releasing a sequence

doall realizes a lazy sequence and returns the realized collection, so all elements remain retained. For side-effecting traversal, dorun also realizes items but returns nil without holding the sequence head. doseq and dotimes likewise return nil by design. section 3.4.5 section 3.4.5

Avoid head retention when processing potentially large lazy sequences:

  • Prefer dorun for realization whose purpose is executing side effects. section 3.4.5
  • Use doall deliberately when retaining the realized collection is required. section 3.4.5

How Clojure: The Essential Reference covers it

How deep it goes
Explains retention behavior and contrasts iteration functions, but does not detail garbage-collector internals.
Examples
Uses doall, dorun, doseq, and dotimes to contrast retaining realized collections with nil-returning traversal.
What it assumes
Assumes familiarity with lazy sequences and realization while explaining their memory advantage and retention risk.
What you can do after
Diagnose/debug with it by spotting iteration patterns that retain lazy-sequence heads and choosing dorun when appropriate.
How it connects
Connects lazy sequences with realization, garbage collection, doall, dorun, doseq, and dotimes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.