Sobes.tech
Middle

Tell me about garbage collection methods.

sobes.tech AI

Answer from AI

Garbage collection methods:

  • Reference Counting: Each object keeps a count of references to itself. When the count reaches zero, the object is considered garbage and is deleted.
    • Advantages: Simple, does not block the main program execution for long.
    • Disadvantages: Cannot handle cyclic references; requires additional space for the counter in each object.
  • Tracing Garbage Collectors: Start with a set of "root" objects (e.g., active variables, call stack) and recursively traverse all objects accessible from these roots. Unreachable objects are considered garbage.
    • Main tracing strategies:
      • Mark and Sweep:
        1. Mark: Traverse the object graph, marking all accessible objects.
        2. Sweep: Second pass through memory, deleting all unmarked objects.
        • Disadvantages: Memory fragmentation.
      • Mark and Compact:
        1. Mark: Same as in Mark and Sweep.
        2. Compact: Moves live objects to make them contiguous, eliminating fragmentation.
        • Disadvantages: More complex, may require stopping program execution.
      • Copying: Divides memory into two regions (semi-spaces). In each garbage collection cycle, live objects from one region are copied to the other. The old region is then fully cleared.
        • Advantages: No fragmentation, fast memory allocation after collection.
        • Disadvantages: Requires twice the memory compared to active usage.
  • Generational Garbage Collection: Based on the hypothesis that most objects live short lives. Memory is divided into generations (young, old). Objects are placed in the young generation upon creation. If an object "survives" several collections in the young generation, it is moved to the old generation. Garbage collection occurs more frequently in the young generation.
    • Advantages: Efficient, as most work is done in the young generation with a small amount of data.
    • Disadvantages: Requires tracking references from old to young generations (cards or other mechanisms).

Examples of languages and their GC:

  • Python: Reference Counting (with cyclic garbage collection for cyclic references).
  • Java, C#: Generational, Mark and Sweep, Mark and Compact, Copying (various options and combinations depending on the specific JVM/.NET version and settings).
  • Go: Concurrent, non-generational Mark and Sweep with optimizations.