GC Threshold: Latency vs. Memory Trade-offs
Adjusting `gc.set_threshold` directly impacts application latency and memory usage. A lower threshold triggers more frequent, smaller collections, reducing peak memory but potentially increasing CPU time and pause frequency. Conversely, higher thresholds decrease collection frequency, saving CPU cycles but allowing memory usage to grow larger between cycles. For example, some applications have seen a 20% faster response time by increasing the threshold from 700 to 50,000, with no memory increase.
The top 3
- Python GC Defaults: Balancing Speed & Space: Python's default `gc.set_threshold(700, 10, 10)` values are a compromise, designed to reclaim memory frequently enough to prevent excessive growth without introducing overly disruptive collection pauses for most applications.
- Real-time Apps: Lowering GC Threshold for Latency: For latency-sensitive applications, decreasing `gc.set_threshold` values forces more frequent, smaller garbage collection cycles, which helps reduce maximum pause times and smooth out performance spikes.
- Memory-Intensive Tasks: Raising GC Threshold for Efficiency: Increasing `gc.set_threshold` allows more objects to accumulate before collection, reducing the frequency of GC cycles and potentially improving overall throughput for memory-intensive applications, though individual pauses might be longer.
Sources
Open the full topic