The mark-compact algorithm

The mark-compact algorithm is used by the garbage collector to maintain the memory. Essentially, it can be classified into three phases:

  • The mark phase: In the mark phase, the garbage collector loops through the different objects in the heap and identifies the one that is being referenced by a root item. A root item can be either the starting point of the program execution or a particular function. If the element is being referenced, it marks the object. All other objects, which are not referenced, are then classified as dead objects.
  • The relocating phase: In the relocating phase, the garbage collector moves all the objects that are being referenced, groups them together, and then updates the memory address for each of the next objects in the memory heap.
    In addition to this, the garbage collector also classifies objects that are being used in the application to one of the different generations.
  • The compacting phase: In the compacting phase, the garbage collector destroys the dead objects classified in the previous phase and reclaims their memory. 

The entire process that the garbage collector undertakes can lead to a performance impact on the application. This is due to the fact that during the program execution, the garbage collector needs to make sure that the references in the heap are not changed during its run. This means that all the other threads of the application are paused while the run is in progress. 

Fortunately, this situation does not arise often as the garbage collector starts cleaning only when the memory available for the application execution is low. Therefore, while the memory is high, the collection algorithm does not kick in. Additionally, as explained while we were discussing generations, when the garbage collection starts, it first checks the generation 0 heap objects. If they survive the cleanup, they are promoted to the next generation. For objects in the higher generations, the garbage collector assumes that the objects in higher generations will probably be used in the application for a longer period of time.

In the next section, we will look at how we can explicitly call the garbage collection method in C#.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.195.183