Go performance tuning is a measure-first process: write a benchmark, profile with pprof, fix the biggest hotspot (usually allocations, lock contention or I/O), and measure again. Most gains come from fewer heap allocations, better data layout, bounded concurrency and efficient I/O, not from micro-tricks.
The Go toolchain ships everything you need: go test -bench, pprof, the execution tracer, benchstat and, since Go 1.21, profile-guided optimization (PGO). This article walks through that workflow with runnable examples.
Never optimise by guessing. Write a benchmark, run it several times and compare the results statistically.
Run go test -bench=. -count=10 > old.txt, change the code, save the new output to new.txt and compare with benchstat old.txt new.txt (installed from golang.org/x/perf/cmd/benchstat). b.Loop() is available from Go 1.24; on older versions use for i := 0; i < b.N; i++. The ReportAllocs call adds B/op and allocs/op columns, which are often more telling than time.
Benchmarks can write profiles directly:
For a running service, import net/http/pprof on an internal-only port:
Then capture a 30-second CPU profile with go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30. Useful profiles are:
| Profile | What it shows | Typical fix |
|---|---|---|
cpu | Where CPU time is spent | Better algorithm, less work in hot loops |
heap / allocs | Who allocates memory | Preallocate, reuse, avoid escapes |
mutex | Contention on locks | Shard locks, shorten critical sections |
block | Waiting on channels and locks | Rework the pipeline, add buffering |
goroutine | Goroutine leaks and pile-ups | Add cancellation and timeouts |
Never expose the pprof endpoints to the public internet. The execution tracer (go test -trace trace.out, then go tool trace trace.out) complements pprof when you need to see scheduling latency or GC pauses over time.
Every heap allocation costs allocation time and later GC work. Check what escapes to the heap with go build -gcflags=-m.
Practical rules:
make([]T, 0, n) and make(map[K]V, n).strings.Builder or bytes.Buffer instead of repeated string concatenation in loops.sync.Pool, but only after a profile shows allocation pressure, and always reset the object before reuse.string and []byte in hot paths.The GC is tunable through GOGC (default 100) and a soft memory limit, GOMEMLIMIT or debug.SetMemoryLimit (Go 1.19+). In containers, set GOMEMLIMIT to roughly 90 percent of the container limit so the GC works harder before the process is OOM-killed. A higher GOGC trades memory for less GC CPU.
Goroutines are cheap, but unbounded concurrency causes memory growth and contention. Use a bounded worker pool or errgroup with a limit:
Since Go 1.22 each loop iteration has its own variable, so capturing it in the closure is safe. For shared counters prefer sync/atomic types such as atomic.Int64 over a mutex; for read-heavy maps consider sync.RWMutex or sharding. Pass a context.Context everywhere so abandoned work stops.
bufio.Reader and bufio.Writer.http.Client and its transport so connections are pooled; set timeouts.io.Copy instead of reading whole bodies into memory.database/sql connection pool limits (SetMaxOpenConns, SetMaxIdleConns), prepared statements and batching.encoding/json is fine for most services, and Go 1.25 added an experimental encoding/json/v2 behind GOEXPERIMENT=jsonv2.fieldalignment analyzer can report waste.Profile-guided optimization uses a real CPU profile to inline hot calls and devirtualize interface calls. Since Go 1.21, put a representative profile named default.pgo in the main package directory and go build uses it automatically (-pgo=auto is the default). The Go team reports improvements typically in the range of a few percent up to around 14 percent, depending on the program, so measure your own.
Other options: build with the current Go release (each release improves the compiler, runtime and GC), use -ldflags="-s -w" only to shrink binaries (it does not speed code up), and never use -race builds for performance numbers.
Reproduce the slowness in a benchmark or load test, then capture a CPU profile with pprof. The profile tells you where time goes, so you fix the real bottleneck instead of a guess.
sync.Pool always make code faster?No. It helps when many short-lived objects of the same type are allocated in hot paths, but it adds complexity and the pool is emptied by the GC. Benchmark with -benchmem before and after.
There is no fixed number. Goroutines themselves are cheap, but each one holds memory and whatever resources it uses, so bound the work by what downstream systems (databases, APIs, CPU cores) can handle.
GOGC?Only when profiles show GC consuming significant CPU or memory limits matter. Start with GOMEMLIMIT in containers, then adjust GOGC and re-measure.
Optimise Go in a loop: benchmark, profile, change one thing, compare with benchstat. Cut allocations, preallocate, bound concurrency, buffer I/O and enable PGO for production builds. Keep the Go toolchain current, because runtime and compiler improvements arrive with every release.