Preliminary Study ----- C # garbage collection mechanism,
Original address: http://mp.weixin.qq.com/s? _ Biz = MzAwNTMxMzg1MA ==& mid = 206721898 & idx = 1 & sn = dfaee0ae6fa092b1a6db5779d75c0a2d & scene = 5 # rd
The following is a brief summary of the above-mentioned articles by cainiao. Of course, there are still many shortcomings. I hope you can better read the articles above!
I. Basic Principles:
Computer memory is roughly divided into two types: Stack and heap. C # is divided into two types: Value Type and reference type. The value type is mainly stored in the stack area (the stack mechanism is actually implemented through a linked list), and the actual memory of the reference type is allocated in the heap queue, however, the stack maintains the actual address of the reference type, similar to the value type storage method, to achieve pointer maintenance.
To instantiate a variable of the reference type, perform the following steps:
1. calculate the total number of bytes required to instantiate the variable
2. Calculate the additional bytes required for the instantiated object (type object pointer and synchronous fast index)
3. CLR checks whether there is sufficient memory
A. Allocate the memory directly if it is sufficient,
B. If the memory is not enough, execute a garbage collection task and check whether the memory is sufficient again. If the memory is insufficient, an OutMemeryException exception is thrown.
2. Check for objects that are no longer in use
Each application has a set of roots, and each root represents a storage object (especially a reference type)
1. In the tag phase, traverse all the roots, recursively set the tag on the synchronization block index of the root referenced by the object
2. Compression stage. In this phase, the garbage collector traverses the heap linearly to find continuous blocks that contain unlabeled objects. If the garbage collector finds a small memory block, it ignores the memory. If a large continuous memory block is found, the garbage collector moves non-junk objects in the memory to these contiguous memory blocks to compress the hosted heap.
3. Concept of Generation
Concept of object generation
Generation 0, the newly created instance, CLR does not perform any checks on it
1 generation, CLR checked once, objects not recycled
Generation 2, CLR checks twice or above, and is still not recycled
The CLR allocates a certain amount of memory space for each generation at the beginning of the program. When the created object finds that the memory is insufficient, a garbage collection mechanism is executed. When the 0-generation memory is sufficient, the inaccessible objects in the 1-generation will not be recycled. Only when the zero-generation memory exceeds the budget will the objects in the first generation be cleared. In this way, the program only needs to mark some objects to implement an effective garbage collection mechanism.