How to Tune Garbage Collector in Go Language ?

ยท ยท 276 words ยท 2 minute read

How to set the GOGC value ? ๐Ÿ”—

You can set its value in the terminal like this.


Or you can change it in yaml file of the environment variable when using docker or kubernetes.

What is the default value of GOGC ? ๐Ÿ”—

The default value of GOGC is 100 which means that the garbage collection process will run when the allocations doubled from previous allocations count.

What can I do to reduce the effect of garbage collection in Go ? ๐Ÿ”—

If your Go program has a large static data set, set the GOGC to a smaller percentage; for example GOGC=50. The more the number the smaller the heap (memory allocation), but the more CPU usage.

If your Go program has a tiny heap, small number of allocations, and a rapid GC. Set GOGC to a higher percentage so the garbage collection will occur less often. Thus, your program will response faster and with lower latency. But it will use more RAM than default setting.

If your program is running for a short period of time like a compiler, it maybe ok to shutdown the garbage collection. You can stop garbage collection by GOGC=off. Thus, the program runs faster, but may explode (terminated due to using more that available/permitted RAM). So it is recommended to profile and measure before and after changing the GOGC value.

Here is the value in a brief table.

large static data setGOGC=50 or lesssmaller heap / less RAMMore CPU
tiny heap, rapid GCGOGC=200 or morelower latencyMore RAM
one-shot executionGOGC=offruns fastermay explode and terminate the program