.NET Garbage Collection Performance Tips Sasha Goldshtein | SELA Group
Why This Talk? The.NET GC is a complex beast Many performance optimizations over the years Still many ways to shoot yourself in the foot Mark and SweepGenerationsLOH Fragmentation HoardingSegments FinalizationBackground GC VMMapPerfView Server GC
Refresher: Tracing GC.NET GC is not based on reference counting GC starts from roots and marks reachable objects as “live” The rest of the heap is swept as garbage Usually holes are compacted and objects are moved around Allocations are very cheap
Problems? Naïve implementation blocks mutators Full GC is very slow (think multi-GB heaps) Result: very long application pauses
GC Flavors CLR 2.0 Workstation GC Concurrent, non- concurrent Server GC Parallel GC CLR 4.0 Workstation background GC CLR 4.5 Server concurrent and background GC DEMO
Generations Full GC is slow and very inefficient – most objects are live New objects die quickly, old objects die hard Divide the heap into regions, enabling partial collections – Tricky to deal with cross-generation references Special area for large objects (>85K)
Measurement Profile apps for allocations, not just time Look for large allocation sources Look for objects with a long lifetime Pool temporary large objects (cf. WCF BufferManager)BufferManager DEMOS
GC and Virtual Memory Windows VirtualAlloc has 64KB granularity in user-mode CLR allocates consecutive 16MB-64MB segments (x86) of memory On x86, easy to fragment the address space VMMap to detect, x64/VM hoarding to fix DEMO
Finalization Finalizer (cleanup) runs automatically after object becomes unreachable Performance problems and bugs: – Allocation/finalization rate – Race conditions, deadlocks – The finalizer may run while a method is still executing on an instance DEMO
Conclusions Minimize the number and size of allocations Strive to quickly kill temporary objects Pool temporary large objects Don’t use finalization. Just don’t use it We have only scratched the surface here! Pro.NET Performance: Maoni Stephens MSDN blog: Advanced.NET Debugging (Hewardt):
Thank blog.sashag.net Sasha Goldshtein | SELA Group Two free Pro.NET Performance eBooks! Send an to with an answer to the following question: What do you need to do for your console application to use background server GC in.NET 4.5?