This is the second day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

Last time, we looked at how reference counting works and the pros and cons, but since modern browsers have abandoned it, we should have a deeper understanding of tag clearing. This article will cover the ins and outs of tag clearing.

Mark clear

Tag clearing is a bit more complicated to implement than reference counting, and the general process is divided into two phases

  1. Mark phase: This phase is used to mark active objects
  2. Clear phase: This phase is used to clear unmarked objects

The realization process of the marking stage is to start from a group of root objects (including but not limited to Window objects and DOM objects in the browser environment), and traverse all referenced objects through reference relations. All traversed objects will be marked, so as to indicate that the object is reachable

The cleanup phase is implemented by iterating through the heap, removing all unmarked objects, resetting the cleanup, and waiting for the next GC

This approach addresses two disadvantages of reference counting:

  1. Counters require a lot of memory: token clearing only requires marking (or not), so it can be done with a single binary bit
  2. The problem with circular references: Token scavenging determines whether objects need to be cleared based on their reachability, so circular references do not affect GC collection

But nothing is perfect, and this kind of solution brings the following problems:

  1. The cleared memory space is discontinuous and fragmented
  2. When you need the memory of a newly allocated object, you need to traverse the memory space to find the appropriate space to store the new object

Because of the above two disadvantages, based on the way of mark clearing, the way of mark compression is derived

This way the mark phase With tag removal is the same, the difference is clear, this scheme will move all of the object’s memory space as a whole to the memory, such as objects and not up to the object’s memory space is respectively occupy a continuous space, and then to remove unreachable object space occupied, That would avoid the problem of space fragmentation. Perfect

conclusion

Technology has always evolved for better experience and is always a process of striving for perfection, so tag compression is not the end of the road. V8 has taken GC to a higher level with its own hack technology. For how it works, please listen to the next breakdown 😉