How to Tune Garbage Collector in Go Language ?

ยท 330 words ยท 2 minute read

How to set the GOGC value ? ๐Ÿ”—

You can set its value in the terminal like this.

GOGC=200

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.

SituationActionProsCons
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

I hope you enjoyed reading this post as much as I enjoyed writing it. If you know a person who can benefit from this information, send them a link of this post. If you want to get notified about new posts, follow me on YouTube , Twitter (x) , LinkedIn , and GitHub .

Share:
waffarx cash back