Optimise Go programs by measuring first, then fixing the biggest cost. Use go test -bench for micro-benchmarks, pprof for CPU, heap and goroutine profiles, and runtime/trace for scheduling problems. The usual wins are fewer allocations, preallocated slices and maps, bounded concurrency, and less contention on shared state.
Guessing at hot spots wastes time. Every technique below should be confirmed with a benchmark or profile before and after the change.
A benchmark lives in a _test.go file and loops b.N times (or uses b.Loop() in Go 1.24 and later). Add b.ReportAllocs() to see allocations per operation.
benchstat (from golang.org/x/perf/cmd/benchstat) compares runs statistically, so you can tell a real improvement from noise. Run benchmarks on a quiet machine and use a realistic input size.
Profiles tell you where time and memory go in a real workload.
For a running service, import net/http/pprof on an internal-only port:
Then fetch a profile with go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30. Useful profiles:
| Profile | Shows | Typical fix |
|---|---|---|
| CPU | Functions using CPU time | Better algorithm, fewer calls |
Heap (alloc_space) | Where allocations come from | Reuse buffers, preallocate |
| Goroutine | Blocked or leaked goroutines | Fix missing cancellation |
| Mutex and block | Lock contention and waits | Shard locks, reduce critical sections |
| Execution trace | Scheduler, GC and latency gaps | Rebalance work, reduce GC pressure |
Never expose /debug/pprof publicly. Go 1.21 and later can also use profile-guided optimisation: place a representative CPU profile as default.pgo in the main package directory and the compiler uses it for inlining and devirtualisation decisions.
Allocation cost shows up twice: in the allocator and in garbage collection. Check which values escape to the heap with go build -gcflags=-m.
make([]T, 0, n) and make(map[K]V, n).strings.Builder, as in the benchmark above, instead of += in a loop.sync.Pool.Always reset pooled objects before returning them, and never keep a reference after Put. The GC may empty a pool at any time, so a pool is a cache, not storage.
For memory-heavy services you can tune the collector with GOGC and the soft limit GOMEMLIMIT (or debug.SetMemoryLimit), for example in containers where you know the memory budget.
Goroutines are cheap, but unbounded goroutines still cost memory and scheduling time. Bound parallel work with a worker pool or errgroup.SetLimit.
errgroup is in golang.org/x/sync/errgroup. Since Go 1.22 each loop iteration has its own variable, so capturing it in a closure is safe. Other points:
context.Context so work stops when the caller gives up.sync/atomic for simple counters and sync.RWMutex for read-heavy data, then confirm with the mutex profile.GOMAXPROCS for CPU-bound work, more for I/O-bound work.bufio.Reader and bufio.Writer to cut system calls.io.Copy instead of reading everything into memory with io.ReadAll.http.Client and its transport so connections are pooled.strconv rather than fmt.Sprintf for simple number conversions in hot paths.slices and maps packages provide generic, well-optimised helpers such as slices.Sort and slices.BinarySearch.No. Write clear code, set a performance target, and optimise only the paths a profile shows are hot. Early tuning adds complexity without a measured benefit.
There is no fixed number. Millions can run, but each holds a stack and any resources it touches. Bound the work when it hits databases, files or remote APIs.
sync.Pool always make code faster?No. It helps for large or frequently allocated temporary objects. For small objects the pool overhead can exceed the allocation cost, so benchmark it.
Compare goroutine profiles over time at /debug/pprof/goroutine?debug=2. Leaks are usually goroutines blocked on a channel or lock that no longer has a sender or cancellation.
Benchmark with go test -bench and benchstat, profile with pprof and runtime/trace, then reduce allocations, bound concurrency, and use buffered I/O. Change one thing at a time and keep the numbers that prove each change helped.