Tuning Python's GC: Thresholds and Disabling
Developers can customize Python's garbage collection frequency using `gc.set_threshold()` or entirely disable the automatic collector with `gc.disable()` for scenarios requiring fine-grained memory control.
The top 3
- Python GC's Default Thresholds Explained: Python's generational garbage collector uses default thresholds of (700, 10, 10). The first number (700) dictates that a Generation 0 collection triggers when allocations minus deallocations exceed this value, while the subsequent 10s determine how many times younger generations must be collected before older ones are swept.
- When to Consider Disabling Python GC: Disabling Python's automatic garbage collection via `gc.disable()` is typically reserved for niche scenarios, such as obtaining more consistent performance benchmarks (used by the `timeit` module) or in specific high-load applications. Instagram famously saw a 10% speed improvement by disabling GC after careful analysis of their Django application's memory patterns.
- Boosting Performance by Adjusting GC Thresholds: Tuning Python's GC thresholds can significantly boost performance. For instance, increasing the Generation 0 allocation threshold (`threshold0`) from its default 700 to 50,000, often combined with `gc.freeze()`, resulted in a 20% faster response time for Talk Python and improved p95 latency by 80-100ms for Close.com, by reducing frequent collection pauses.
Sources
Open the full topic