Sobes.tech
Middle+

Tell me about Garbage Collector in Go — algorithm, optimization methods.

sobes.tech AI

Answer from AI

Go uses a concurrent, trigger-based garbage collector with a mark-and-sweep algorithm. It runs in parallel with the main goroutines, minimizing pauses.

Main features of GC in Go:

  • Parallel and incremental: the collector works alongside the program, breaking work into small parts.
  • Trigger-based: it starts when a certain memory usage threshold is reached.
  • Three-phase process: marking reachable objects, sweeping unreachable ones, updating metadata.

Optimization methods:

  • Minimize allocations: reuse objects, use object pools (sync.Pool).
  • Avoid holding references: release references to objects so GC can collect them.
  • Configure GOGC: environment variable or runtime/debug.SetGCPercent controls the GC trigger threshold (reducing it lowers delays but increases frequency).
  • Profiling: use pprof to analyze allocations and identify bottlenecks.

Example of using a pool to optimize allocations:

var bufPool = sync.Pool{
    New: func() interface{} {
        return make([]byte, 1024)
    },
}

func process() {
    buf := bufPool.Get().([]byte)
    defer bufPool.Put(buf)
    // use buf
}