Senior
Tell about garbage collection in Go.
sobes.tech AI
Answer from AI
Go uses a concurrent, trigger-based garbage collector with a mark-and-sweep algorithm that runs in parallel with the program execution (concurrent GC). This minimizes pause times for garbage collection and maintains low latency.
Main features:
- Automatic memory management — developers do not need to explicitly free memory.
- Parallel operation — the garbage collector runs concurrently with main goroutines.
- Incremental and trigger-based — collection is triggered when a certain memory usage threshold is reached.
Example of simple code where the garbage collector frees unused memory:
package main
import (
"fmt"
"runtime"
)
func main() {
var m runtime.MemStats
// Create a large slice
data := make([]byte, 10<<20) // 10 MB
fmt.Println("Allocated 10MB")
// Release the reference
data = nil
// Manually trigger garbage collection
runtime.GC()
runtime.ReadMemStats(&m)
fmt.Printf("HeapAlloc = %v MiB\n", m.HeapAlloc/1024/1024)
}
In this example, after nullifying the reference and calling runtime.GC(), the memory occupied by the slice will be freed.