liveBook · Manning

Snapshot-compare pattern

As explained in Fast by Default

The snapshot-compare pattern is a diagnostic method that compares memory snapshots taken before and after a self-contained operation to identify retained allocations.

The snapshot-compare pattern diagnoses retained allocations by comparing memory snapshots before and after a self-contained operation. It is especially useful for long-lived sessions and single-page applications, where navigation does not clear the page and small leaks accumulate. section 7.1.3

Apply the pattern systematically:

  • Run garbage collection when the tool supports it, then take a baseline heap snapshot. section 7.1.3
  • Perform the isolated operation, such as navigating away from a view and returning, or processing a backend batch. section 7.1.3 section 7.2.4
  • Take a second snapshot and compare added, deleted, and net memory by object type, file, or line number. section 7.1.3 section 7.2.4
  • Repeat the operation several times: proportional growth indicates accumulation, while stable totals suggest normal cleanup. section 7.2.4

Large positive deltas point toward likely retention sources: unreleased event listeners, closures retaining DOM nodes or large data, unbounded caches, timers that survive component removal, request-scoped data stored process-wide, unreleased connections, or unread response bodies. section 7.1.3 section 7.2.4

Backend batch check with tracemalloc

Start tracemalloc, capture snapshot_before, run process_batch(data), capture snapshot_after, and compare the snapshots by line number. A line growing by 50 KB on every request is suspicious; a one-time increase that levels off may be normal. section 7.2.4

Figure 7.4 The snapshot-compare-investigate pattern for memory profiling and leak detection.

Use the investigation flow to connect snapshot capture, comparison, and leak diagnosis. section 7.1.3

How Fast by Default covers it

How deep it goes
Explains capture, comparison, repetition, and interpretation, stopping short of prescribing fixes for each retention source.
Examples
Uses article navigation, social widgets, repeated batch operations, and tracemalloc allocation listings.
What you can do after
Diagnose/debug with it by locating allocation growth and distinguishing persistent leaks from memory that levels off.
How it connects
Connects heap snapshots, garbage collection, memory leaks, event listeners, closures, caches, timers, and tracemalloc.

Related concepts

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