Generational GC Control via `set_threshold` Parameters

The three parameters in `gc.set_threshold(threshold0, threshold1, threshold2)` control Python's generational garbage collection. `threshold0` dictates when Generation 0 is collected, `threshold1` determines when Generation 1 is collected (after `threshold0` collections), and `threshold2` similarly controls Generation 2 collection.

The top 3

  1. Python's Default GC Thresholds Explained: By default, Python's `gc.set_threshold` is `(700, 10, 10)`. This means Generation 0 is collected after 700 net object allocations, Generation 1 after 10 Generation 0 collections, and Generation 2 after 10 Generation 1 collections, prioritizing frequent collection of short-lived objects.
  2. Tuning `threshold0` for High-Churn Applications: Lowering `threshold0` (the first parameter) causes more frequent, smaller Generation 0 collections, which can reduce memory usage and pause times in applications with rapid object creation and destruction, like web servers. Conversely, increasing it (e.g., to 50,000 from 700) can reduce GC overhead for stable applications.
  3. Trade-offs for `threshold1` and `threshold2`: Increasing `threshold1` and `threshold2` (for Generations 1 and 2) reduces the frequency of older generation collections. This can decrease CPU overhead for applications with many long-lived objects by letting them survive longer, but it risks increased memory footprint if unreferenced objects are retained for extended periods.

Sources

Open the full topic