GC algorithm classification

  • Reference counting
  • Mark clear
  • Tag to sort out
  • Generational recycling

Implementation principle of reference counting algorithm

Each object is assigned a reference technique at creation time that counts the number of times the object is referenced. When the number of references is zero, the object can be reclaimed immediately. The advantages and disadvantages:

1, when the object reference is 0, it can be recycled immediately to reduce the page lag. 2, the object referenced by loop cannot be recycled. 3, counters must be created for each objectCopy the code

The realization principle of tag clearing algorithm

All reachable objects are traversed starting at the root node and marked as active, and the object is traversed a second time, clearing the unmarked objects and the previously marked objects

The advantages and disadvantages:

(1) Useless objects cannot be recycled immediately. (2) Recycled objects can be recycled. (3) Recycled addresses are not consecutiveCopy the code

You can see that the memory collected in the blue area is discontinuous.

Mark finishing algorithm

Is an enhanced version of the tag clearing algorithm. Before recycling, the addresses of reclaimed objects and non-reclaimed objects are sorted out to ensure that the reclaimed addresses are continuous

The advantages and disadvantages:

1. Object 2 cannot be reclaimed immediately, and the reclaimed addresses are continuousCopy the code