My account

Speed and memory in Go

Optimizing Go starts with measuring, not guessing. If you understand benchmarks and benchstat, pprof profiles, the stack and the heap and escape analysis, reducing allocations, using sync.Pool the right way, the garbage collector with the GOGC and GOMEMLIMIT settings, and memory leaks with slices and goroutines, you can answer most interview questions.

Not reviewedWritten with AI helpReading time: 20 minOnline shop exampleGo 1.25 code

Author: bezzad

Contents

The problem: a service that gets slow during a sale

Our order service is fast on normal days. But on a sale day:

  1. The CSV export of orders takes a minute, and CPU goes to 100%.
  2. Kubernetes kills the pods (OOMKilled), even though the live data of the program is less than half of the memory limit.
  3. The memory of one pod goes up day by day, even when traffic is low.

A teammate suggests running everything in parallel with goroutines and adding sync.Pool everywhere. Before any change, we must measure where the problem is. In this lesson we see how.

Measure first

The first rule of optimizing: do not guess. Most of the time the slow part is where you do not expect it.

  1. Write a benchmark for the suspect code, with real data.
  2. Take a profile to see where time and memory really go.
  3. Change only that part, and measure again.
func BenchmarkOrdersCSV(b *testing.B) {
	orders := fakeOrders(20_000)
	for b.Loop() {
		writeOrdersCSV(io.Discard, orders)
	}
}
go test -bench OrdersCSV -benchmem -count 10 > new.txt
benchstat old.txt new.txt
  1. The benchmem flag also shows the number of allocations and bytes per run. Fewer allocations usually mean less work for the garbage collector.
  2. The count flag runs each benchmark several times. The benchstat tool computes the mean and the spread, and tells you if a difference is real or noise.

Profiling with pprof

The pprof tool shows where the program spends its time. There are several kinds of profiles:

Profile What it shows When to use it
CPU profile Which functions use CPU time The service is slow or CPU is high.
Heap profile Which lines took memory (live or total) Memory is high or the GC works a lot.
Goroutine profile Which line each goroutine is on right now The number of goroutines keeps growing.
Block and mutex profiles Where goroutines wait for locks or channels The service is slow but CPU is low.

In a service, the net/http/pprof package makes these profiles available over HTTP:

import _ "net/http/pprof" // registers /debug/pprof/

func main() {
	// Internal port only: never expose pprof publicly.
	go http.ListenAndServe("localhost:6060", nil)
	// ... start the real server on :8080 with its own mux
}
go tool pprof -http=:8081 \
  http://localhost:6060/debug/pprof/profile?seconds=30
  1. This import registers the pprof paths on DefaultServeMux. The main server must have its own mux, so these paths do not become public.
  2. Never open pprof on a public port. It shows internal details of the program, and a CPU profile can add extra load.
  3. The http flag opens a web UI with a flame graph.
Box width = share of CPU timeExportOrders 100%ordersCSV 82%TodayOrders 17%concatstrings 48%gcBgMarkWorker 23%Sprintfmemmove 44%Wide box on top: the place to optimizeThe numbers are only an exampleBottom: caller. Top: callee
In a flame graph, the width of each box is that function's share of CPU time. Wide boxes at the top are the places to optimize. Here most time goes to copying strings and to the garbage collector.

In our example, the profile showed that most time went to ordersCSV, and inside it to copying strings (memmove) and to the garbage collector, not to the database. Running it in parallel with goroutines would not have helped here.

The stack, the heap and escape analysis

Go has two places for variables:

  1. The stack belongs to each goroutine. When a function returns, its space is freed at no cost.
  2. The heap is shared. The garbage collector must find what is not used anymore and free it.

The compiler decides by itself where each variable goes. This is called escape analysis. If a variable is still needed after the function returns, it “escapes” to the heap:

func total(items []Item) int {
	sum := 0 // stays on the stack
	for _, it := range items {
		sum += it.Price
	}
	return sum
}

func newItem(sku string) *Item {
	it := Item{SKU: sku}
	return &it // escapes: lives after the function returns
}
go build -gcflags=-m ./...
# ./main.go:19:2: moved to heap: it
Goroutine stackHeap memorytotal(items)sum intnewItem(sku)return &itit ItemThe garbage collector must free itmoved to heap: itFreed for free when the function returnsAnything that lives after the function returns escapes to the heap
The variable sum lives only inside the function and stays on the stack. The variable it is returned by pointer, so it goes to the heap and the garbage collector must free it.

Common reasons to escape to the heap:

  1. Returning a pointer to a local variable.
  2. Putting a value in an interface, for example passing it to fmt.Println or storing it in an any.
  3. Capturing a variable in a closure that lives after the function, for example a goroutine.
  4. A size that is not known at compile time, for example make with a length that comes from the input.

These are not bad. They are only worth checking on hot paths (code that runs millions of times).

Reducing allocations

Our first bug came from a loop with “out +=” on a string. Each time a new string was made and all of the old text was copied. Some common ways to allocate less:

// Preallocate when you know the size.
ids := make([]int64, 0, len(orders))
for _, o := range orders {
	ids = append(ids, o.ID)
}

// Build strings with a Builder, not with +=.
var sb strings.Builder
sb.Grow(len(orders) * 32)
for _, o := range orders {
	sb.WriteString(strconv.FormatInt(o.ID, 10))
	sb.WriteByte('\n')
}
report := sb.String()
  1. Give the slice its capacity at the start if you know the size. Otherwise append makes a bigger array and copies several times.
  2. Use strings.Builder to build strings. Even better: write directly to an io.Writer, like the HTTP response.
  3. Avoid fmt.Sprintf on hot paths. The strconv functions are faster and allocate less.
  4. Remove needless conversions between string and byte slices. Each conversion is usually a copy.

The sync.Pool type

The sync.Pool type keeps temporary objects for reuse:

var bufPool = sync.Pool{
	New: func() any { return new(bytes.Buffer) },
}

func render(o Order) []byte {
	buf := bufPool.Get().(*bytes.Buffer)
	defer bufPool.Put(buf)
	buf.Reset()
	writeOrder(buf, o)
	return bytes.Clone(buf.Bytes()) // copy: buf goes back
}
  1. It only helps when a profile shows that a temporary object is made many times on a hot path.
  2. The garbage collector may clear the pool in any cycle. So a pool is not a cache. Do not use it to keep data.
  3. Reset the object before reuse, and do not keep any reference to it after Put.
  4. Do not put very large objects back in the pool, or one big buffer holds memory forever.

The garbage collector, GOGC and GOMEMLIMIT

The Go garbage collector runs concurrently with the program (mark and sweep). Its stop-the-world pauses are usually very short, but its work takes a share of the program’s CPU. It has two main settings:

  1. The GOGC variable (default 100) says how much the heap may grow after the last cycle before the next cycle starts. 100 means when the heap is about twice the live data. A bigger number means less CPU for the GC but more memory.
  2. The GOMEMLIMIT variable (since Go 1.19) is a soft limit for all memory of the runtime. Near the limit, the GC runs earlier.
TimeMemoryContainer memory limitGOMEMLIMITLive dataGOGC=100Each time up to twice the live dataMore live dataGC runs earlierGOGC sets the growth rate, GOMEMLIMIT sets the soft limit
With GOGC at 100, the heap grows to about twice the live data. Near GOMEMLIMIT, the garbage collector runs earlier, so the pod does not reach the container memory limit.

This was our second bug. The live data was 600 MB, and the container limit was 1 GB. With GOGC at 100, the heap grew to about 1.2 GB, and Kubernetes killed the pod. The fix:

env:
  - name: GOMEMLIMIT
    value: "900MiB" # a bit below the container limit
  1. Set GOMEMLIMIT a bit below the container limit, so there is room for other memory (stacks, code).
  2. If the live data is really bigger than the limit, GOMEMLIMIT does not help. The GC runs again and again and burns CPU. Then you need more memory or less data.
  3. Since Go 1.25 the default GOMAXPROCS looks at the CPU limit of the container on Linux. The same version also added a new experimental garbage collector called Green Tea.

Memory leaks

Our third bug was memory that was never freed. Go has a garbage collector, but you can still leak memory:

// Bad: keeps the whole 10 MB file alive
func firstLine(data []byte) []byte {
	i := bytes.IndexByte(data, '\n')
	return data[:i]
}

// Good: copy the small part
func firstLine(data []byte) []byte {
	i := bytes.IndexByte(data, '\n')
	return bytes.Clone(data[:i])
}
  1. A small slice of a big array keeps the whole array alive. If you keep it in a cache, you hold 10 MB instead of 100 bytes.
  2. Stuck goroutines are never collected. The goroutine profile shows thousands of goroutines on one line.
  3. Caches without a limit, for example a map that only grows, are slow leaks. Give them a size limit and an expiry time.
  4. To find a leak, take two heap profiles some time apart and compare them with the base flag. A line that keeps growing is the problem.

Common mistakes

Mistake Result The right way
Optimizing without measuring Time is wasted on the wrong part. Benchmarks and pprof first
Running a quadratic loop in parallel The same extra work, on more cores Fix the algorithm first.
Building a string with += in a loop Many copies and pressure on the GC strings.Builder, or writing to an io.Writer
Using sync.Pool everywhere Complex code with no gain Only for a hot object a profile showed
Opening pprof on a public port Data leaks and extra load Internal port only
No GOMEMLIMIT in a container OOMKilled with little live data A value a bit below the container limit
Keeping a small slice of a big buffer The whole buffer stays alive. Copy with bytes.Clone or slices.Clone
Comparing one benchmark run A decision based on noise Several runs and benchstat

Summary in seven lines

  1. Measure first: a benchmark with real data, a pprof profile, and a comparison with benchstat.
  2. The CPU profile shows time, the heap profile shows memory, the goroutine profile shows leaks. Do not make pprof public.
  3. The compiler decides with escape analysis what goes to the heap. See it with the m flag.
  4. On hot paths, give capacity at the start, use strings.Builder, and use less fmt.
  5. The sync.Pool type is not a cache. Use it only for a hot temporary object, after measuring.
  6. GOGC sets how fast the heap grows, and GOMEMLIMIT prevents OOM in a container.
  7. Memory leaks through small slices of big arrays, stuck goroutines and caches without a limit.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.