Sobes.tech
Senior

Tell about the garbage collector in Go.

sobes.tech AI

Answer from AI

In Go, the garbage collector (GC) is responsible for automatic memory management, freeing unused objects to prevent memory leaks.

Features of GC in Go:

  • Parallel and concurrent: operates alongside the program execution, minimizing pauses.
  • Three-phase process: marking (identifying reachable objects), sweeping (removing unreachable objects), and compacting memory.
  • Fine-tuning: you can control the frequency and aggressiveness of collection through environment parameters.

An example of using GC in Go does not require explicit invocation, but you can trigger collection manually:

package main
import (
    "runtime"
    "fmt"
)
func main() {
    var m runtime.MemStats
    runtime.ReadMemStats(&m)
    fmt.Printf("Allocated before GC: %v bytes\n", m.Alloc)
    runtime.GC() // manual trigger of garbage collection
    runtime.ReadMemStats(&m)
    fmt.Printf("Allocated after GC: %v bytes\n", m.Alloc)
}

Thus, GC in Go helps developers manage memory, increasing the reliability and performance of applications.