Let’s start with the garbage collection algorithm

1. Mark – Clear

The algorithm is divided into two stages: marking stage and clearing stage. The mark phase marks all objects that need to be reclaimed, and the clear phase recycles all marked objects. Disadvantages:

  • This can result in a large amount of memory space for fragments, resulting in a waste of resources.
  • It’s inefficient and takes up a lot of time.

2. Mark – Tidy

There are also two stages: the mark stage, which marks all objects that need to be reclaimed. In the collation phase, all surviving objects are moved towards the boundary, and objects outside the boundary are directly reclaimed. Disadvantages: Although the memory discontinuity is solved to a certain extent, the efficiency is still low.

3. Replication algorithm

In order to solve the problem of efficiency, there is a copy algorithm. The replication algorithm needs to divide the memory into two parts of the same size, and only store objects in one part of the memory at a time. When this part of the memory is full, you only need to copy the surviving objects to another part of the memory, and then empty the original part of the memory.

4. Generational algorithm

Generational algorithms are a concept that uses different garbage collection algorithms for different generations. For example, if the new generation triggers garbage collection more frequently and generally has fewer surviving objects, the replication algorithm can be used. However, in the old age, general objects live for a long time and need to occupy a large amount of space, so it is not suitable for the replication algorithm. You can choose Mark-Tidy or Mark-clear based on your requirements.