Sasha Goldshtein
CTO
Sela Group
@goldshtn
blog.sashag.net
Garbage Collection
Performance Tips
www.devconnections.com
GARBAGE COLLECTION PERFORMANCE TIPS
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 Sweep Generations LOH
Fragmentation Hoarding Segments
Finalization Background GC
VMMap PerfView Server GC
2
www.devconnections.com
GARBAGE COLLECTION PERFORMANCE TIPS
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
3
www.devconnections.com
GARBAGE COLLECTION PERFORMANCE TIPS
PROBLEMS?
Naïve implementation blocks mutators
Result: very long application pauses
4
www.devconnections.com
GARBAGE COLLECTION PERFORMANCE TIPS
GC FLAVORS
CLR 2.0
Workstation GC
•Concurrent, non-
concurrent
Server GC
•Parallel GC
CLR 4.0
Background
workstation GC
CLR 4.5
Concurrent and
background
server GC
5
www.devconnections.com
GARBAGE COLLECTION PERFORMANCE TIPS
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)
6
www.devconnections.com
GARBAGE COLLECTION PERFORMANCE TIPS
MEASUREMENT
Profile apps for allocations, not just time
Look for large allocations, long-lived objs
Pool temporary large objects
7
www.devconnections.com
GARBAGE COLLECTION PERFORMANCE TIPS
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
8
www.devconnections.com
GARBAGE COLLECTION PERFORMANCE TIPS
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
9
www.devconnections.com
GARBAGE COLLECTION PERFORMANCE TIPS
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
10
www.devconnections.com
GARBAGE COLLECTION PERFORMANCE TIPS
ADDITIONAL REFERENCES
www.devconnections.com
GARBAGE COLLECTION PERFORMANCE TIPS
THANK YOU!
Sasha Goldshtein @goldshtn
sashag@sela.co.il blog.sashag.net
12

.NET Garbage Collection Performance Tips