Sobes.tech
Senior

How does the Garbage Collector work in Go?

sobes.tech AI

Answer from AI

Garbage Collector (GC) in Go is an automatic memory management mechanism that frees unused objects to prevent memory leaks.

Main features of GC in Go:

  • Three-phase collection:

    1. Mark: GC scans all root objects (stack, global variables) and marks all reachable objects.
    2. Sweep: All objects not marked are considered unreachable and are freed.
    3. Concurrent: GC runs in parallel with the program execution, minimizing pauses.
  • Reachability tracing: GC uses a tracing algorithm to determine which objects are still needed.

  • Minimal pauses: Go GC is optimized for low latency, which is important for server applications.

Here's how the GC cycle roughly works:

1. The program runs, allocating memory.
2. GC is triggered, stopping goroutines for a short time (stop-the-world).
3. It marks all reachable objects.
4. It resumes the program while concurrently cleaning up unused memory.

Thus, developers do not need to manually free memory, reducing errors related to memory management.