Advanced Go

Memory and Garbage Collection

Reason about reachability, escape analysis, allocation, retention, and resource cleanup without relying on myths.

What you will learn

By the end of this lesson, you will be able to:

  • distinguish language semantics from compiler allocation decisions;
  • explain reachability-based garbage collection;
  • inspect escape-analysis diagnostics without treating them as permanent guarantees;
  • find common sources of accidental retention;
  • decide when reducing allocations is worth the complexity.

Values first, storage second

Write correct code using Go's value, pointer, and ownership semantics. The compiler decides whether storage can remain associated with a goroutine stack or must be allocated on the heap.

Returning a pointer to a local value is safe:

func newCounter() *int {
    value := 0
    return &value
}

The compiler ensures the value remains valid. Do not rewrite correct code merely because “locals belong on the stack.”

Reachability

The garbage collector can reclaim heap objects that are no longer reachable from live program roots. It does not know whether a reachable object is still logically useful.

If a global cache, goroutine, map, or slice keeps a reference, the object remains reachable.

Garbage collection handles memory, not every resource. Files, response bodies, database rows, locks, and external leases require explicit lifecycle handling.

Escape analysis

The compiler analyses whether values must escape their current scope. Inspect diagnostics with a compiler flag in a real Go environment:

go build -gcflags=-m=3 ./...

The output explains inlining and escape decisions. It can be noisy. Use it after a profile identifies allocation pressure in relevant code.

Escape decisions are compiler implementation details and may change with code shape, target, and Go version. Correctness must not depend on them.

Interfaces and allocations

Converting a value to an interface does not guarantee a heap allocation, nor does it guarantee the absence of one. The compiler considers how the interface value is used.

Measure the actual operation with benchmarks and allocation reporting rather than using a universal rule.

Slice retention

A small subslice can keep a much larger backing array reachable:

func prefix(data []byte) []byte {
    return data[:16]
}

If data is several megabytes and the returned prefix lives for a long time, the entire backing array may remain reachable.

Copy when the lifetime difference matters:

func copiedPrefix(data []byte) []byte {
    length := min(16, len(data))
    result := make([]byte, length)
    copy(result, data[:length])
    return result
}

The copy costs CPU and a small allocation but can release a large backing array sooner. Measure the real trade-off.

Goroutine retention

A blocked goroutine keeps its stack and referenced values alive. Goroutine leaks are therefore also memory-retention problems.

Every goroutine needs a clear completion or cancellation path. Monitor goroutine counts and capture profiles when growth is unexplained.

Reuse and sync.Pool

sync.Pool holds temporary objects that may be removed at any time, especially around garbage collection. It is not a durable cache and provides no guarantee that a stored item will be returned.

It can reduce pressure for frequently allocated temporary objects shared across goroutines, after profiling proves the benefit. Pooled objects must be reset so data does not leak between uses.

Garbage collector controls

The runtime exposes controls such as GOGC and a soft memory limit. Their exact behaviour and tuning guidance belong to runtime documentation and can evolve.

First reduce accidental retention, bound caches and queues, and profile allocation hot spots. Tuning cannot fix unbounded ownership.

Common mistakes

  • Equating pointers with heap allocation: escape depends on use, not syntax alone.
  • Calling every retained object a GC bug: reachable references usually explain retention.
  • Forcing zero allocations everywhere: complexity grows while irrelevant code becomes harder to maintain.
  • Pooling objects containing secrets without complete reset: data can cross requests.
  • Using finalizers for ordinary cleanup: timing is nondeterministic; explicit close/release remains necessary.
  • Optimising from -gcflags output alone: compiler diagnostics do not show user impact.

Practice

Write a function that reads a large byte slice and returns its first line. Create one version that returns a subslice and one that copies. Explain the lifetime trade-off, then design a benchmark that reports time, bytes, and allocations without claiming which is better before measurement.

Summary

  • Compiler storage decisions are implementation details; write correct value semantics first.
  • The collector reclaims unreachable memory, not reachable data that your program forgot to release logically.
  • Escape diagnostics explain current compiler decisions but do not replace profiles.
  • Subslice and goroutine lifetimes can retain much larger object graphs.
  • Reduce allocations only when evidence shows a meaningful result.

Official reference: A Guide to the Go Garbage Collector.

Ready to wrap up?

Mark this complete when you can explain the main idea and finish the practice task.

Copyright © 2026