.NET › Diagnostics & Performance

How would you profile and reduce excessive garbage collection pauses affecting application latency?

Advanced

Answer

Start by using dotnet-counters or a gcdump/trace to confirm GC is actually the bottleneck (high gen-0/gen-1 collection frequency, or notable gen-2/full GC pause times), then investigate allocation hotspots via a trace analyzed in PerfView or Visual Studio's allocation profiler to find code paths allocating excessively (often boxing, unnecessary intermediate collections, or large object heap allocations) -- common fixes include reducing allocations in hot paths (using Span<T>, object pooling, or avoiding LINQ in tight loops), and for latency-sensitive apps, considering Server GC's SustainedLowLatency mode or tuning GC settings.
// Reducing allocations in a hot path using object pooling
private static readonly ObjectPool<StringBuilder> _pool =
    new DefaultObjectPoolProvider().Create<StringBuilder>();

public string BuildMessage() {
    var sb = _pool.Get();
    try {
        sb.Append("...");
        return sb.ToString();
    } finally {
        sb.Clear();
        _pool.Return(sb);
    }
}
Real-world example A latency-sensitive trading application reduces p99 response time significantly after profiling reveals excessive gen-0 allocations from creating new StringBuilder instances on every request, fixed by adopting an ObjectPool to reuse instances instead.

Common follow-ups: What is SustainedLowLatency GC mode and when is it appropriate?;How does the Large Object Heap (LOH) affect GC pause characteristics differently from the normal heap?