Hello colleagues! Today I would like to talk about the "lungs" of Golang - its Garbage Collector (GC). While this topic is well-known and frequently discussed, since I've taken on the goal of gradually exploring the most important components of the language, I couldn't skip it.

Introduction

The Garbage Collector (GC) in Go is often called "non-ideal" due to its relative simplicity compared to more complex implementations in other programming languages, but this doesn't mean it's ineffective for real applications.

On the contrary, the language development team made a very deliberate and well-reasoned choice in favor of implementation simplicity and behavior predictability, consciously sacrificing some theoretically possible optimizations to create a more reliable and understandable memory management system.

How Does GC Work in Go?

Golang uses a concurrent, tri-color Mark-and-Sweep algorithm. Let's examine its working principle in more detail. As the name suggests, this algorithm has 2 phases:

  1. Mark Phase - GC marks all reachable objects using three colors: white, gray, and black:
  2. Sweep Phase - removal of all white objects that remained after marking. This operation is performed concurrently with the application's execution.

Abstractions and Concepts

Stop The World (STW) Pauses

Modern GC in Go has very short STW pauses - averaging <0.5ms for most programs. This is achieved through:

Comparison with Other Languages

Java (JVM GC): JVM offers a wide range of GCs (G1, CMS, Parallel, ZGC, Shenandoah), which are often much more complex and configurable. Some of them also aim for low latency (ZGC, Shenandoah) but usually require more attention to configuration. Go GC is simpler by design and less configurable, with an emphasis on "working out of the box". Java GC can lead to longer STW pauses in certain scenarios, although modern implementations have significantly improved.