Mark & Sweep Garbage Collection

Created: 2022-12-22T00:52:13-06:00

Return to the Index

Conservative: walks the stack and considers everything that looks like a pointer to be a pointer. Checks if the GC has handed out any memory at that location and marks it if so.

Tracing: starts from a set of roots and walks only through traceable handles in those structures. More efficient but requires tracing code be created to manage it.

Mark: go through the program's active memory and "mark" any reachable objects with a flag.

Sweep: go through the GC's allocated memory pool and deallocate any block which has an incorrect mark. The only way that a mark is wrong is because it could not be traced from a root so it is now safe to kill the block.

Compacting collectors move objects and are obligated to replace all tracing pointers to the new location. They however avoid memory fragmentation.

Generational collectors retain multiple memory pools. Each pool has a separate lifecycle so that recently allocated objects (which are believed to be more likely to be garbage) are checked frequently while objects that have survived multiple collections are migrated to another pool which is checked less frequently.