gc.set_threshold(): Python GC's Key Tuning Lever

Adjusting the three thresholds in `gc.set_threshold()` directly controls the frequency of Python's generational garbage collection. Increasing the first threshold (defaulting to 700) can significantly reduce GC runs, leading to performance improvements of 20% or more in applications with many short-lived objects by allowing reference counting to handle more deallocations before a full GC cycle is triggered.

The top 3

  1. Default vs. Optimized `gc.set_threshold` Values: Python's default `gc.set_threshold` is typically (700, 10, 10), triggering frequent collections for newly created objects. Increasing the first threshold, for instance to (50000, 10, 10), can significantly reduce GC overhead and improve application speed by allowing more objects to be collected via reference counting before a full GC cycle.
  2. Performance Gains from GC Threshold Tuning: Optimizing `gc.set_threshold` can lead to measurable performance improvements, such as a 20% faster response time in some web applications or a reduction in garbage collection utilization from ~3% to ~0.5% of total runtime, by reducing the frequency of costly full GC cycles.
  3. 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.

Sources

Open the full topic