How GoLang Garbage Collection Works

How GoLang Garbage Collection Works

Garbage Collection (GC) is like a magical cleanup crew for programming languages. It automatically frees up memory that’s not being used, so you don’t have to worry about it. In Go, a popular programming language, there’s a unique way this GC works. Let’s break it down into simpler terms. In this article, Golang Tutorial, we will deep dive into How GoLang Garbage Collection Works.

Garbage Collection (GC) is a mechanism that automatically frees up memory by reclaiming objects that are no longer in use. Golang uses a special method known as “tracing garbage collection”. Let’s unravel the concept of GC in Go with simpler explanations.

How GoLang Garbage Collection Works

Golang Garbage Collection Pointer

Garbage collection in Go revolves around the concept of reachability. When an object is no longer reachable, it is considered garbage and will be collected in the next cycle. Reachability is determined by tracing all accessible pointers starting from the root set, which includes global variables and active goroutines’ local variables.

Here’s a deep dive into Go garbage collection with respect to pointers, accompanied by examples:

1. Basic Example

type Person struct {
    Name string
    Age  int

func main() {
    person := &Person{Name: "John", Age: 25}

    person = nil

In the above example:

  • We create a pointer to a Person object, and it’s reachable via the person variable.
  • After setting person to nil, the Person object is no longer reachable, making it eligible for garbage collection.

2. Slices and Underlying Arrays

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    numbers = numbers[:2]



  • We create a slice of integers numbers.
  • After we reslice numbers to only include the first two elements, the underlying array still holds all five integers, so no garbage is created.
  • If you had done numbers = nil, the entire underlying array would become unreachable and would be garbage collected.

3. Circular References

Even with circular references, Go’s garbage collector can detect that objects are no longer used and free the memory.

type Node struct {
    Value string
    Next  *Node

func main() {
    nodeA := &Node{Value: "A"}
    nodeB := &Node{Value: "B", Next: nodeA}
    nodeA.Next = nodeB

    // Even though there's a circular reference, once we null out the entry points
    // the entire structure becomes unreachable.
    nodeA = nil
    nodeB = nil

In the above example, nodeA and nodeB reference each other, creating a circular link. However, after setting both to nil, the entire structure is unreachable and will be garbage collected.

4. Maps and Pointers

type Student struct {
    ID   int
    Name string

func main() {
    students := make(map[int]*Student)
    students[1] = &Student{ID: 1, Name: "Alice"}

    delete(students, 1)

After deleting the entry from the map:

  • The Student object with ID 1 is no longer reachable through the students map and is eligible for garbage collection.

In Go, the garbage collector tracks object reachability by tracing pointers. If an object can’t be reached by following a series of pointers starting from root objects, it’s considered garbage. It’s crucial for developers to understand how pointers work to ensure efficient memory management, even in a language with a garbage collector like Go.

Golang Garbage Collection (How GoLang Garbage Collection Works)

1. What’s This “Tracing” All About?

Firstly, when we say “garbage collection” in Go, we’re mostly talking about “tracing garbage collection.” This means that the GC figures out which parts of memory (called objects) are still being used by tracing or following a series of pointers (like a treasure hunt). Anything not touched by this treasure hunt is considered “garbage” and can be cleaned up.

2. Basic Terms:

  • Object: Think of it as a box in your computer’s memory that contains Go values.
  • Pointer: It’s like an arrow that shows the way to a box (object). So when you hear “pointer”, imagine it’s showing you where an object is in memory.
  • Object Graph: All the objects and the pointers connecting them make up the object graph. It’s like a big map of all boxes and arrows.

These objects and pointers together form what’s called an “object graph.” This graph is like our treasure map. The GC uses this map to figure out which boxes are still valuable and which ones are just taking up space.

3. How Does The GC Decide What to Clean? How does Go’s GC Work?

The GC has a two-step cleaning process: How GoLang Garbage Collection Works

  • Mark: It goes on its treasure hunt, marking every box (object) it finds as “valuable.” Go starts from known pointers (like global or local variables) and marks all the objects it can reach from these pointers. It’s like starting from your home and marking every place you can reach using a map.
  • Sweep: After the hunt, it looks at all the boxes. The ones not marked as “valuable” are considered garbage and thrown away, freeing up space. After marking, Go looks at all the objects and cleans up those that were not marked. It’s like throwing away boxes that no one is pointing to.

This method is called “mark-sweep.” And remember, Go’s GC doesn’t shuffle around the boxes (objects) like some other clean-up crews might. It just marks and sweeps.

4. The GC Cycle:

The GC doesn’t work non-stop. It has breaks! It goes through three main phases: sweeping (cleaning), taking a break, and then marking (treasure hunting). This repeating sequence is known as the GC cycle.

5. Costs of Running the GC:

Think of the GC as a machine that uses fuel (CPU time) and space (memory). Sometimes it might use more fuel but less space, and other times more space but less fuel. There’s a trade-off.

The important thing is that Go allows you to tweak how much fuel and space the GC should use, to get the best performance for your specific needs.

There’s a price to pay for this cleaning service:

  1. CPU Time: Your computer’s brain (the CPU) needs time to do the marking and sweeping.
  2. Memory: Keeping track of all the objects and pointers requires extra memory.

In simple words, you can think of it as a balance. If you do the cleaning frequently, you’ll use less memory, but your CPU will be busier. If you clean less often, you’ll use more memory, but your CPU will have more free time.

6. GOGC – The Magic Knob:

GOGC is like a control knob that you can turn to change the behavior of the GC. By adjusting GOGC, you’re telling the GC when to start its next treasure hunt. A higher GOGC means the GC will wait longer to start its hunt, using more space but less fuel. A lower GOGC means it’ll start its hunt sooner, using less space but more fuel.

You can change the GOGC setting with an environment variable or through Go’s programming tools. If you want, you can even turn off the GC altogether (though this isn’t recommended unless you’re sure about it).

How GoLang Garbage Collection Works

GOGC is like a dial you can turn to tell Go when to start its cleaning. By adjusting GOGC, you’re deciding on the trade-off between CPU time and memory use.

  • Higher GOGC Value: More memory is used before cleaning starts. This means fewer cleanups but higher memory use.
  • Lower GOGC Value: Less memory is used before cleaning starts. This means more frequent cleanups but lower memory use.

You can also turn the cleaning off with GOGC=off, but this means memory can keep increasing if you’re not careful.

Indeed, one of the characteristics of many garbage collectors, including the one used by Go, is the “Stop The World” (STW) event. This event is a brief period when the execution of a program is halted so the garbage collector can perform certain tasks without interference from running threads.

However, the Go team has worked diligently to minimize the duration and impact of these STW pauses, making them as short as possible.

What does “Stop The World” mean in Go’s GC?

Golang garbage collection stop the world, In the context of Go’s garbage collection, STW means that all goroutines (Go’s lightweight threads) are paused for a brief moment. This ensures a consistent view of memory, which is necessary for certain garbage collection operations, particularly during the marking phase.

Why are STW pauses necessary?

While it might seem counter-intuitive to stop all program execution, even briefly, this consistency guarantees that no new pointers are being created or changed, which could complicate the task of the garbage collector. If the GC and the program’s goroutines were running concurrently all the time, the GC would have to account for changes made by those goroutines, which would make its job much more complex and potentially less efficient.

Go’s Efforts to Minimize STW

Starting from Go 1.5 onwards, the garbage collector was redesigned to be concurrent, meaning it does most of its work while the application is running. This significantly reduced the duration of STW pauses.

The GC in Go operates mainly in two phases:

  1. Mark phase: This is where live objects (those still in use) are identified. While most of this phase is concurrent, it begins and ends with a short STW pause.
  2. Sweep phase: This phase removes the objects identified as garbage. It’s fully concurrent, meaning it runs alongside your program’s goroutines without stopping them.

Managing STW in Real-World Applications

For most applications, the STW pauses in Go’s GC are short enough to be unnoticeable. However, for applications with very high uptime requirements or those that need to process large amounts of data with low latency, it’s important to be aware of these pauses.

To manage and potentially reduce STW pauses:

  1. Profiling: Use Go’s built-in pprof tool to profile your application and understand its memory usage. This can help in identifying areas of the code that generate excessive garbage, leading to more frequent GC runs.
  2. Tuning: Adjust the GOGC environment variable to change the aggressiveness of the garbage collector.
  3. Optimization: Reduce the amount of garbage your application creates. For instance, by reusing objects or using structures that generate less garbage.
  4. Monitoring: Keep an eye on GC metrics. This includes not only the frequency and duration of STW pauses but also the overall time spent in garbage collection.

In summary, while Go’s garbage collector does introduce STW pauses, they are typically very short and have been continually optimized for minimal disruption. Still, it’s beneficial for developers to understand and manage these pauses, especially in performance-critical applications.


Garbage Collection in Go is all about managing memory efficiently. By understanding the basics of how it works and the trade-offs involved, you can optimize your Go programs to run faster and smoother.

Imagine your computer’s memory as a room. Over time, you bring in boxes (objects). Some boxes are used often, while others just sit around gathering dust. The garbage collector is like a cleaner who comes in, checks which boxes are still useful (marking), and then takes away the unused boxes (sweeping). The frequency of this cleaner’s visits is controlled by the GOGC dial. Adjusting this can help you find a good balance between the room’s cleanliness and how often the cleaner interrupts you.

Thank you for reading!

Dive into this insightful post on CodingReflex to unlock the power of Quarkus, Java’s revolutionary framework for building ultra-speed applications.

  • For real-time updates and insights, follow our tech enthusiast and expert, Maulik, on Twitter.
  • Explore a universe of knowledge, innovation, and growth on our homepage, your one-stop resource for everything tech-related.

For more information on related topics, check out the following articles: