How would you find and reduce excessive memory allocation and garbage collection in a .NET service?
PhonePe · Full Stack Developer · 3-4-years · technical
Published
Year not specified · .NET, C#, Software Engineering
Community answers
Posted by wasAsked editorial collection
Measure first. Observe allocation rate, heap size, Gen 0/1/2 collections, large-object-heap size, pause time, and request latency with `dotnet-counters`; capture a trace or dump to identify allocating call stacks and retained objects. A high allocation rate and a memory leak are different: a leak shows objects remaining reachable after collections.
Common reductions include avoiding repeated materialization, streaming large results, reusing buffers through `ArrayPool<T>`, removing unnecessary string conversions, and selecting collections with sensible capacity.
```csharp
public static async Task CopyAsync(Stream input, Stream output, CancellationToken ct)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(64 * 1024);
try
{
int read;
while ((read = await input.ReadAsync(buffer.AsMemory(0, buffer.Length), ct)) > 0)
await output.WriteAsync(buffer.AsMemory(0, read), ct);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer, clearArray: true);
}
}
```
Do not pool small objects blindly; pooling adds lifetime and thread-safety complexity. Benchmark the changed hot path and confirm that allocation savings improve real latency or throughput rather than shifting cost elsewhere.
Prince Yadav · · 0 likes
Measure first, then remove allocations from the hot paths.
1. Confirm the problem
- dotnet-counters monitor -p <pid> System.Runtime shows allocation rate, GC heap size, Gen 0/1/2 counts, % time in GC and LOH size.
- Symptoms: high CPU with a high % time in GC, latency spikes during Gen 2 collections, steadily growing memory.
2. Find the allocations
- dotnet-trace with the gc-verbose profile, PerfView, or Visual Studio / JetBrains dotMemory allocation views show which methods allocate most.
- dotnet-gcdump or a memory snapshot helps when memory grows (a leak), showing which objects are retained and by whom.
- BenchmarkDotNet with [MemoryDiagnoser] measures allocations of specific methods before and after changes.
3. Typical culprits and fixes
- String building in loops: use StringBuilder, string.Create or interpolated string handlers; avoid repeated Substring and Split — use Span<char> and ReadOnlySpan<char>.
- LINQ in hot loops: each operator allocates enumerators and delegates; use plain loops where it matters.
- Boxing: value types passed as object or non-generic interfaces; use generics.
- Large temporary arrays: rent from ArrayPool<T>.Shared and return them; use RecyclableMemoryStream for streams.
- Closures capturing variables in lambdas allocate; use static lambdas where possible.
- Serialization: System.Text.Json with source generators reduces allocations; stream large payloads instead of buffering whole strings.
- Logging: use LoggerMessage source generators or check IsEnabled to avoid formatting strings that are never written.
- Unbounded caches and static collections: add size limits and expiration.
- Event handlers not unsubscribed: they keep objects alive.
4. Runtime settings
- Server GC for throughput services; consider DATAS (dynamic adaptation, default in .NET 9+) for container density; set memory limits correctly in containers.
5. Validate
- Compare allocation rate, GC counts and p99 latency before and after under the same load test. Optimise only code that shows up in profiles — readability matters elsewhere.