Garbage collection is a crucial aspect of Go's memory management system. It automatically frees up memory that is no longer in use, allowing developers to focus on writing code rather than manual memory management.
Go uses a concurrent, tri-color mark-and-sweep garbage collector. This approach minimizes program pauses while efficiently managing memory. The garbage collector runs concurrently with the main program, reducing the impact on performance.
The garbage collection process in Go follows these steps:
Go's runtime automatically triggers garbage collection based on various factors, including:
While Go's garbage collector is efficient, it can still affect program performance. To minimize its impact:
Here's a simple example that demonstrates how to observe garbage collection events:
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
// Enable GC logging
runtime.SetGCPercent(10)
// Allocate memory to trigger GC
for i := 0; i < 10; i++ {
_ = make([]byte, 1000000)
time.Sleep(time.Millisecond * 10)
}
// Print GC stats
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
fmt.Printf("Number of GC cycles: %d\n", stats.NumGC)
}
This example creates memory allocations to trigger garbage collection and then prints the number of GC cycles that occurred.
Go's garbage collection system is a powerful feature that simplifies memory management for developers. By understanding its workings and following best practices, you can write efficient Go programs that make the most of this automatic memory management system.
For more advanced topics related to Go's memory management, explore Go Memory Management and Go Profiling.