How to Tune Garbage Collector in Go Language ?
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.
Situation | Action | Pros | Cons |
---|---|---|---|
large static data set | GOGC=50 or less | smaller heap / less RAM | More CPU |
tiny heap, rapid GC | GOGC=200 or more | lower latency | More RAM |
one-shot execution | GOGC=off | runs faster | may 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 .