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.
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:
- The CSV export of orders takes a minute, and CPU goes to 100%.
- Kubernetes kills the pods (OOMKilled), even though the live data of the program is less than half of the memory limit.
- 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.
- Write a benchmark for the suspect code, with real data.
- Take a profile to see where time and memory really go.
- 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
- The benchmem flag also shows the number of allocations and bytes per run. Fewer allocations usually mean less work for the garbage collector.
- 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
- This import registers the pprof paths on DefaultServeMux. The main server must have its own mux, so these paths do not become public.
- Never open pprof on a public port. It shows internal details of the program, and a CPU profile can add extra load.
- The http flag opens a web UI with a flame graph.
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:
- The stack belongs to each goroutine. When a function returns, its space is freed at no cost.
- 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
Common reasons to escape to the heap:
- Returning a pointer to a local variable.
- Putting a value in an interface, for example passing it to fmt.Println or storing it in an any.
- Capturing a variable in a closure that lives after the function, for example a goroutine.
- 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()
- Give the slice its capacity at the start if you know the size. Otherwise append makes a bigger array and copies several times.
- Use strings.Builder to build strings. Even better: write directly to an io.Writer, like the HTTP response.
- Avoid fmt.Sprintf on hot paths. The strconv functions are faster and allocate less.
- 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
}
- It only helps when a profile shows that a temporary object is made many times on a hot path.
- The garbage collector may clear the pool in any cycle. So a pool is not a cache. Do not use it to keep data.
- Reset the object before reuse, and do not keep any reference to it after Put.
- 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:
- 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.
- The GOMEMLIMIT variable (since Go 1.19) is a soft limit for all memory of the runtime. Near the limit, the GC runs earlier.
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
- Set GOMEMLIMIT a bit below the container limit, so there is room for other memory (stacks, code).
- 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.
- 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])
}
- 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.
- Stuck goroutines are never collected. The goroutine profile shows thousands of goroutines on one line.
- Caches without a limit, for example a map that only grows, are slow leaks. Give them a size limit and an expiry time.
- 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
- Measure first: a benchmark with real data, a pprof profile, and a comparison with benchstat.
- The CPU profile shows time, the heap profile shows memory, the goroutine profile shows leaks. Do not make pprof public.
- The compiler decides with escape analysis what goes to the heap. See it with the m flag.
- On hot paths, give capacity at the start, use strings.Builder, and use less fmt.
- The sync.Pool type is not a cache. Use it only for a hot temporary object, after measuring.
- GOGC sets how fast the heap grows, and GOMEMLIMIT prevents OOM in a container.
- Memory leaks through small slices of big arrays, stuck goroutines and caches without a limit.