Making GO Garbage Collector uncomplicated

Carlos Abdalla
2 min readFeb 28, 2023

--

What is Garbage Collector (a.k.a. GC)

Garbage Collection is the process of reclaiming memory that is no longer in use by the program. Go uses a concurrent, `tri-color`, mark-sweep, which means that it runs concurrently with the program, uses three colors to track objects, and identifies unreachable objects by marking them and sweeping them away.

So.. What the heck are Mark and Sweep?

Mark and Sweep is an algorithm….
Go’s GC uses it, which involves two phases.

  1. In the marking phase, the garbage collector traverses the object graph to identify all the reachable objects and mark them. This phase is concurrent with the app, which means that the app will continue to execute while the GC is running.
  2. In the sweeping phase, the GC frees the memory occupied by the unreachable objects. The sweeping phase is not concurrent with the app and therefore, the program is paused while the GC is sweeping.

Tuning Garbage Collection

Although Go’s GC is optimized for performance, it may not be suitable for all workloads. For example, applications that generate a lot of short-lived objects may experience pauses during garbage collection, which can affect the application’s responsiveness. In such cases, tuning the garbage collector can help improve performance.

Go provides several environment variables that can be used to tune the garbage collector. These variables include GOGC, which controls the ratio of heap growth to heap size, and GODEBUG, which provides detailed information about the garbage collector’s behavior.

Take a look at GOMEMLIMIT

Parallel Marking

Parallel marking is a feature of Go’s GC that allows multiple threads to mark objects concurrently. This feature improves the efficiency of the garbage collector, especially when dealing with large heaps. Parallel marking is enabled by default in Go 1.5 and later versions.\

Concurrent Sweeping

Concurrent sweeping is another feature of Go’s GC that allows the program to run concurrently with the sweeping phase. Concurrent sweeping reduces the amount of time the program is paused while the garbage collector is freeing memory. Concurrent sweeping is enabled by default in Go 1.8 and later versions.

Final Thoughts

Garbage collection is a crucial aspect of memory management in Go. Go’s garbage collector is designed to be efficient and optimized for performance. However, it may not be suitable for all workloads, and tuning may be necessary to achieve optimal performance. Understanding how garbage collection works and how to tune it can help developers write efficient and scalable Go programs. In addition, Go’s garbage collector includes several features, such as parallel marking and concurrent sweeping, that further improve its performance and efficiency.

--

--