Sobes.tech
Senior

How does the garbage collector in Go work? When does it run? Can it be run manually?

sobes.tech AI

Answer from AI

Garbage collector (GC) in Go is a trigger-based, concurrent, mark-and-sweep garbage collector.

How it works:

  • During program execution, GC runs periodically to find and free unused memory.
  • First, the marking phase (mark) occurs, where GC marks all reachable objects.
  • Then, the sweeping phase (sweep) frees memory occupied by unreachable objects.

When it runs:

  • GC is triggered automatically when the allocated memory reaches a certain threshold, depending on current usage and settings.

Can it be triggered manually:

  • Yes, you can manually invoke the garbage collector using the runtime.GC() function from the runtime package.

Example of invocation:

package main

import (
    "runtime"
)

func main() {
    // Explicitly trigger garbage collection
    runtime.GC()
}

However, frequent manual calls to GC are not recommended as they can negatively impact performance.

How does the garbage collector in Go work? When does… - sobes.tech