Garbage Collection in .Net
Wenjin Xu
AgendaBasicsAllocationCollectionFinalizationGC ModeSample
BasicIdea
Automatic memory managementTerms
Domain, Heap, Generation 0, Generation 1, Generation 2, Large object heap
Heap
AllocationInitial
CLR reserve memory for small object heap and large object heap(16MB / 64MB)
newobjAllocate memory from heap
Generation Promotion
CollocationWhen
Generation 0 is fullCall GC.Collect()Low memory
HowAssume all objects are garbageMark following object are reachable:Static fieldsMethod parametersLocal variablesCPU registersStrong ReferencesCollect
Finalization
WhenGeneration 0 is fullCall GC.CollectLow memoryAppDomain unloadCLR is shutting down
Dispose
GC Mode
10
GC Mode
GC
Workstation Server
ConcurrentCollections
“Normal”Background GC
GC Mode - DefaultSingle processor should use default Mode
GC Mode – Concurrent GCIn background garbage collection, ephemeral generations (0 and 1) are collected as needed while the collection of generation 2 is in progress
GC Mode – Server ModeHigh priority threadGC together, so garbage collection is fasterServer garbage collection often has larger size segments
Pinned ObjectWhy do we need pinning
Interop with unmanaged codeHow objects get pinned
GCHandleType.PinnedAllowed by language syntax, eg. fixed in c#Args get pinned by the interop frame
Fragmentation problem
Domain MonitoringCan not disable after enableGlobalPerformance hunt (about <1%)Does not count memory from Marshal.AllocHGlobal
Memory LeakStrong ReferenceAllocate Memory by Marshal
Sample查看性能计数器使用对象池节省新建对象造成的 GC压力使用 VSTS检查内存分配情况WinDBG + sosDebug vs Release
ResourcePerformance Counter
http://msdn.microsoft.com/en-us/library/x2tyfybc.aspx
BookCLR via C# 3rd Edition
Source Codehttp://referencesource.microsoft.com/netframework.aspx
Thank you