Level: AdvancedGo Lang

Go Garbage Collector and Memory Explained

9 min read
Go Garbage Collector featured image: stack, heap and the GOGC setting

The Go garbage collector cleans up memory that your program no longer uses, so you never call free by hand. In this post, you will learn how Go decides where values live and how the collector finds unused memory. Then we will measure it with real tools and cut down allocations in a simple benchmark.

This lesson builds on Go pointers explained and Go slices and arrays explained. We also point to Go profiling with pprof when you need deeper tools. So if pointers feel new, read that post first.

What Is the Go Garbage Collector?

In short, the Go garbage collector, or GC, is a part of the runtime. Its job is to free memory you no longer need. When your code creates a value on the heap, the GC keeps track of it. Later, when nothing points to that value, the GC reclaims the space.

Think of a restaurant with a helper who clears tables. Guests leave plates and glasses behind. Then the helper removes them once the guests are gone. Meanwhile, the kitchen keeps cooking. Similarly, the Go garbage collector cleans up while your program keeps running.

Go’s collector is concurrent, which means it runs at the same time as your code. As a result, pauses are very short, usually well under a millisecond for typical programs. For that reason, the Go garbage collector suits web servers and other low-latency services.

Why the Go Garbage Collector Matters

You do not manage memory by hand in Go, but memory still affects speed. So here is why the Go garbage collector is worth understanding.

  • Fewer bugs: you cannot forget to free memory or free it twice.
  • Predictable latency: short pauses keep web servers responsive.
  • Tuning knobs: two settings let you trade memory for speed.
  • Faster code: fewer allocations mean less work for the GC.
  • Better debugging: you can explain why a service uses too much memory.

Because of this, most Go performance work begins with a simple question: how many allocations does this code make?

How the Go Garbage Collector Works

Go values live in one of two places. First, local values that do not outlive their function usually go on the stack. The stack is cheap and cleaned up automatically. Second, values that must live longer go on the heap, and only the heap needs the GC. The compiler decides this during escape analysis.

Go Garbage Collector diagram showing the stack, the heap and the mark and sweep step
Short-lived values sit on the stack and vanish when a function returns. Values that escape live on the heap, where the garbage collector marks the reachable ones and frees the rest.

When the heap grows enough, the collector starts a cycle. First, it marks every value that your program can still reach, starting from global variables and goroutine stacks. Then it sweeps the heap and frees everything that was not marked. Because most of this work runs beside your code, the program barely stops.

Stack vs Heap

The two memory areas behave very differently, so the table below compares them.

FeatureStackHeap
SpeedVery fastSlower
Cleaned up byFunction returnGarbage collector
SizeSmall per goroutine, grows as neededLarge, shared
Used forShort-lived local valuesValues that outlive the function
GC costNoneYes

So you want most values on the stack. Fortunately, the compiler does that for you whenever it can prove the value does not escape.

What Makes a Value Escape

A value escapes to the heap when its address outlives the function. For example, returning a pointer to a local variable forces the variable onto the heap. Storing a value in an interface can also make it escape. The same is true when you send it on a channel or capture it in a closure. Fortunately, you can check the compiler’s decision with go build -gcflags=-m.

Go Garbage Collector: GOGC vs GOMEMLIMIT

Go gives you two settings to tune the collector. However, they answer different questions, as the table below shows.

FeatureGOGCGOMEMLIMIT
Question it answersHow much can the heap grow before the next cycle?What is the most memory the process should use?
Default100 (heap can double)Off
Higher or bigger valueFewer GC cycles, more memoryMore memory allowed before extra GC
Typical useTrade memory for CPUStay inside a container limit
Set withGOGC=200 or debug.SetGCPercentGOMEMLIMIT=1GiB or debug.SetMemoryLimit
Go Garbage Collector diagram comparing GOGC with GOMEMLIMIT
GOGC decides how far the heap may grow before the next collection, while GOMEMLIMIT sets a soft upper limit for total memory use.

So when should you use which? Start with the defaults, because they suit most programs. Later, use GOMEMLIMIT in containers so the GC works harder before the system kills your process. On the other hand, raise GOGC only when you have spare memory and want less CPU use.

Go Garbage Collector Hands-On: Measure and Reduce Memory

Now let’s watch the collector at work. Because we run small programs on Go 1.24, every number below is real.

Step 1: See Stack and Heap Decisions

First, here are two small functions. One returns a pointer. In contrast, the other keeps its value local.

type User struct {
	ID   int
	Name string
}

// escapes returns a pointer, so the value must live on the heap.
func escapes() *User {
	u := User{ID: 1, Name: "Asha"}
	return &u
}

// stays keeps the value local, so it can live on the stack.
func stays() int {
	u := User{ID: 2, Name: "Ravi"}
	return u.ID
}

Now build with go build -gcflags=-m . and look for the key line. As a result, the compiler tells you exactly what moved.

./main.go:17:2: moved to heap: u

Line 17 is the u inside escapes. In contrast, the u inside stays never appears in the list. That means it stays on the stack, so the GC never has to track it.

Step 2: Watch the Heap with MemStats

Next, we allocate about 20 MB, drop the references and force a collection. Then we print the heap size at each step. This shows the Go garbage collector doing its work.

func stats(label string) {
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	fmt.Printf("%-14s heap=%4d KB  gc runs=%d\n", label, m.HeapAlloc/1024, m.NumGC)
}

func main() {
	stats("start")

	data := make([][]byte, 0)
	for i := 0; i < 200; i++ {
		data = append(data, make([]byte, 100*1024)) // 100 KB each
	}
	stats("after alloc")

	data = nil // drop the references
	runtime.GC()
	stats("after GC")
}

The output below is real.

start          heap=  71 KB  gc runs=0
after alloc    heap=20883 KB  gc runs=3
after GC       heap=  72 KB  gc runs=4

The heap grew to about 20 MB. Meanwhile, the collector ran three times on its own. After we set data = nil and called runtime.GC(), the heap dropped back to 72 KB. This shows that the collector frees memory only when nothing points to it.

Step 3: Watch GC Cycles with gctrace

Meanwhile, the GODEBUG=gctrace=1 setting prints one line for every cycle. For example, this is the first line from our run.

gc 1 @0.015s 4%: 0.10+1.2+0.077 ms clock, 0.20+0.70/0.47/0+0.15 ms cpu, 3->3->1 MB, 4 MB goal, 0 MB stacks, 0 MB globals, 2 P

Let’s read the key parts. First, the 0.10+1.2+0.077 ms clock part shows two tiny pauses around a concurrent mark. Next, 3->3->1 MB gives three heap sizes. They are the size at the start, the size at the end of marking and the live data that remained. Finally, 4 MB goal is the heap size that triggers the next cycle.

Step 4: Reuse Memory with sync.Pool

If your code creates many short-lived buffers, a sync.Pool lets you reuse them. As a result, the GC has less to clean. For example, a busy web server can reuse one buffer per request instead of making thousands of new ones.

var pool = sync.Pool{New: func() any { return make([]byte, 0, 4096) }}

buf := pool.Get().([]byte)
buf = append(buf[:0], "reuse me"...)
fmt.Println("pooled buffer:", string(buf))
pool.Put(buf[:0])

The pool may drop items at any GC, so never store anything in it that you cannot recreate.

Step 5: Preallocate to Cut Allocations

Finally, the simplest trick is to give make the size you expect. To prove it, this benchmark builds a slice of 1000 numbers two ways.

func BenchmarkAppendNoHint(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		var s []int
		for j := 0; j < 1000; j++ {
			s = append(s, j)
		}
	}
}

func BenchmarkAppendWithHint(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		s := make([]int, 0, 1000)
		for j := 0; j < 1000; j++ {
			s = append(s, j)
		}
	}
}

As a result, we see a huge difference on our machine.

BenchmarkAppendNoHint-2     	  150099	      9946 ns/op	   25208 B/op	      12 allocs/op
BenchmarkAppendWithHint-2   	 2041651	       577.4 ns/op	       0 B/op	       0 allocs/op

Without a size hint, the slice made 12 allocations as it grew. With a hint, it allocated nothing on the heap and ran about 17 times faster. Your numbers will differ. However, the pattern is the same everywhere.

Common Mistakes with the Go Garbage Collector

  • **Calling runtime.GC() in production code**: this forces a full cycle and hurts speed. So use it only in tests and demos, and let the Go garbage collector decide when to run.
  • Ignoring allocations in hot loops: small allocations add up quickly. Therefore, check -benchmem for hot paths.
  • Holding references too long: a global map that only grows keeps everything alive. Instead, delete entries you no longer need.
  • Slicing a huge array for a tiny result: the small slice keeps the whole array alive. So copy the small part out.
  • Guessing instead of measuring: tuning without data often makes things worse. Use benchmarks and pprof first.

Best Practices for the Go Garbage Collector

  • Measure before you tune, because most programs run fine with the defaults.
  • Preallocate slices and maps when you know the size, since it avoids repeated growth.
  • Pass small structs by value, because they can stay on the stack.
  • **Set GOMEMLIMIT in containers**, so the process stays under its limit.
  • **Reuse buffers with sync.Pool** in hot paths, but keep the code simple.
  • **Run go build -gcflags=-m** on slow code, since it shows what escapes.

Practice Task

To practise the Go garbage collector, write a function that builds a slice of 100000 strings. Benchmark it with and without a size hint, and then compare the allocs/op numbers. After that, print runtime.MemStats before and after.

Hint: use b.ReportAllocs() in the benchmark. After that, run the program with GODEBUG=gctrace=1 and count how many cycles each version triggers.

Official Resources

These pages explain the collector and its settings, and they also cover the tools used in this lesson.

Quick Recap

  • The Go garbage collector frees heap memory that nothing points to.
  • Escape analysis decides whether a value lives on the stack or the heap.
  • The collector marks reachable values and sweeps the rest, mostly beside your code.
  • GOGC controls heap growth, and GOMEMLIMIT sets a soft memory limit.
  • Fewer allocations mean less GC work, so preallocate and reuse buffers.
  • Always measure with benchmarks, MemStats and gctrace before tuning.

What’s Next?

By now, you understand how Go manages memory. However, good code also needs a good shape. So next, we will put everything together and learn how to organise a real project with clean architecture.

Next up: Go clean architecture for real projects