Managed Heaps

In general it can be categorized into 1) SOH and 2) LOH.  size lower than 85K will be in SOH, size larger than 85K will be in LOH.

Small Object Heap

GC will do 1) Mark 2) Sweep 3) Compact on SOH.

How GC works

When a small object is created (less than 85KB in size), it is stored in the small object heap. The CLR organizes the small object heap into three generations – generation 0, generation 1, and generation 2 – that are collected at different intervals. Small objects are generally allocated to generation 0, and if they survive a GC cycle, they are promoted to generation 1. If they survive the next GC cycle, they are promoted to generation 2.

Further, garbage collection of the small object heap includes compaction, meaning that as unused objects are collected, the GC moves living objects into the gaps to eliminate fragmentation and make sure that the available memory is contiguous. Of course, compaction involves overhead – both CPU cycles and additional memory for copying objects. Because the benefits of compaction outweigh the costs for small objects, compaction is performed automatically on the small object heap.

GC uses generational garbition collection. .Net will device memory into 3 generations. Gen 0 is the youngest one, Gen 2 is the olddest one.

Gen 0 collection will empty Gen 0 for sure. Either move the objects to Gen 1, or Die and compact the rootless objects.

Gen 1 collection will scan gen 0 and gen 1 both, for objects still has root reference, move them from gen 0 to gen 1, and move the ones in gen 1 to gen 2.  

Gen 2 is a full collection because all of the generations are inspected and colleted. 

Gen 0, Gen 1 and Gen 2 are 10 times difference compared to each other.

Some object may have un-managed resources, so these objects will have their reference added to the Finalization Queue.  There is a seperate thread other than GC which will run and call Finalize () method to recycle the objects.

For rootless objects, collect them. in SOH, compact the available space.  in LOH, it does not do compaction, but it will maintain a free memory table.  next time, when there is a object > 85KB, it will check free table firstly, if it can accomodate the object, save it, if not, do fragmentation and allocate new memory.

 

posted on 2018-02-19 05:05  xuyanran  阅读(161)  评论(0编辑  收藏  举报