How do I tune GOGC and GODEBUG settings?

In Go (Golang), tuning the garbage collector settings can greatly help in optimizing the performance of your application. The two main environment variables you can adjust for this purpose are GOGC and GODEBUG.

Understanding GOGC

GOGC is a percentage that controls the garbage collection threshold. The default value is 100, which means the garbage collector will try to keep the heap size at approximately the same size as the most recent allocation plus 100%. Setting a higher value will result in less frequent garbage collection but may increase memory usage.

Setting GOGC

To set the GOGC value, you can do so in your terminal before running your Go application:

export GOGC=200 # Increase the threshold to 200%

Understanding GODEBUG

GODEBUG is a key environment variable that allows you to tweak various settings within the Go runtime, including garbage collection. Some useful settings are:

  • gctrace=1: Enable garbage collection tracing, which provides detailed garbage collection statistics.
  • gcstoptheworld=1: Forces garbage collection to stop the world for a specific period.
  • gcstats=1: Outputs additional GC statistics.

Setting GODEBUG

To configure GODEBUG, do so as shown below:

export GODEBUG=gctrace=1 # Enable GC trace logs

GOGC GODEBUG Golang garbage collector performance tuning memory management