How to stop the golang gc and trigger it manually?

30,444

Package documentation of runtime contains all the details you need:

The GOGC variable sets the initial garbage collection target percentage. A collection is triggered when the ratio of freshly allocated data to live data remaining after the previous collection reaches this percentage. The default is GOGC=100. Setting GOGC=off disables the garbage collector entirely. The runtime/debug package's SetGCPercent function allows changing this percentage at run time. See https://golang.org/pkg/runtime/debug/#SetGCPercent.

So you may set the environment variable GOGC to a percent which is the ratio of freshly allocated data to live data remaining after the previous collection.

When the above data ratio reaches the value of GOGC, a (garbage) collection is initiated. The initial setting is taken from the GOGC env variable, or 100 if the variable is not set. The value off disables garbage collection.

At runtime you can change the GOGC ratio by calling debug.SetGCPercent(), pass a negative value to disable it:

debug.SetGCPercent(-1)

You may trigger a garbage collection "manually" with runtime.GC().

Completely disabling GC might not be what you want though. Read the complete package doc of runtime where you find details about how to fine-tune GC and how to trace GC runs. Analyze them and act accordingly.

Also note that Go 1.7 was released today with improved garbage collector:

Programs should run a bit faster due to speedups in the garbage collector and optimizations in the standard library. Programs with many idle goroutines will experience much shorter garbage collection pauses than in Go 1.6.

If you haven't, first test your application compiled with Go 1.7 before taking any further action.

Share:
30,444

Related videos on Youtube

Han Fei
Author by

Han Fei

Updated on July 21, 2020

Comments

  • Han Fei
    Han Fei almost 4 years

    Currently I'm supporting big table join on a database written in golang. But the gc costs too much time. I want to close the go gc and trigger it manually. How to config the go build args?