What parameters can be used to configure garbage collector behavior?
sobes.tech AI
Answer from AI
In Go (Golang), the garbage collector (GC) is mainly configured through runtime environment parameters and special functions from the runtime package. The main parameters for configuring the garbage collector's behavior:
-
GOGC— sets the percentage increase of the heap at which garbage collection is triggered. The default value is 100, which means GC runs when the heap size doubles. Decreasing this value increases the frequency of collections, raises CPU usage, but reduces latency. -
runtime.GC()— a function to forcibly run the garbage collector. -
runtime.SetGCPercent(int)— programmatically sets theGOGCvalue at runtime. -
GODEBUG— an environment variable that can include various debug options for GC, such asgctrace=1to output statistics.
Example of setting a parameter in code:
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Println("Current GC percent:", runtime.SetGCPercent(-1)) // get current value
runtime.SetGCPercent(50) // reduce the GC trigger threshold
}
Thus, the main parameter for configuring the garbage collector's behavior in Go is GOGC (or runtime.SetGCPercent), which controls the frequency of GC runs based on heap growth.