Optimise Go programs in this order: measure with the built-in profiler and benchmarks, fix the biggest cost (usually allocations, I/O or lock contention), then scale out with concurrency that is bounded and cancellable. Guessing without data wastes time, because Go's compiler and runtime are already fast and the bottleneck is rarely where you expect.
This guide walks through the standard tools (testing, pprof, trace), the most effective code-level techniques and how to scale a service across cores and machines. It targets current Go (1.22 and later).
Write a benchmark next to the code you want to improve:
Run it with go test -bench . -benchmem. The output shows time per operation, bytes and allocations per operation. b.Loop() needs Go 1.24; on older versions write for i := 0; i < b.N; i++. Compare runs before and after a change with benchstat from golang.org/x/perf.
To find hotspots in a running program, profile it:
In a server, import net/http/pprof on an internal-only port to capture CPU, heap, goroutine and mutex profiles from a live process. go tool trace shows scheduler behaviour and GC pauses over time.
Every heap allocation costs time now and garbage collection later. The most reliable wins:
make([]T, 0, n) when you know the count.strings.Builder instead of repeated +=.go build -gcflags=-m to see escape analysis decisions.sync.Pool.string and []byte in hot loops.A sync.Pool may drop items at any garbage collection, so it is only a cache, never storage. Pool only objects that are allocated often and are expensive enough that the benchmark shows a gain.
The garbage collector can be tuned with GOGC (default 100) and a soft memory limit through GOMEMLIMIT, available since Go 1.19. In containers, setting GOMEMLIMIT slightly below the container limit avoids out-of-memory kills.
An algorithm change beats micro-optimisation. A map lookup instead of a linear scan, a strings.Builder instead of repeated concatenation, or a batched database query instead of one query per row often gives 10x or more.
Struct layout matters on hot paths: ordering fields from largest to smallest reduces padding, and the fieldalignment analyzer reports wasteful structs. Keep data you read together contiguous, for example a slice of structs instead of a slice of pointers to structs, which improves CPU cache use.
Since Go 1.21 the slices and maps packages provide generic, well-optimised helpers such as slices.Sort, slices.BinarySearch and slices.Contains.
Goroutines are cheap, but unbounded concurrency overloads databases, networks and memory. Limit parallelism and tie every goroutine to a context:
errgroup comes from golang.org/x/sync. For CPU-bound work, a worker count near runtime.GOMAXPROCS(0) is a good start. Reduce lock contention by narrowing critical sections, using sync.RWMutex for read-heavy data, sync/atomic for counters, or sharding a map. The mutex and block profiles show where goroutines wait.
Most services are limited by I/O, not CPU. Reuse a single http.Client so connections are pooled, always close response bodies and set timeouts. Buffer file and network writes with bufio, stream large payloads with io.Copy instead of reading them fully into memory and batch database operations. A connection pool such as the one in database/sql should be sized with SetMaxOpenConns and SetMaxIdleConns to match what the database can handle.
A stateless Go service scales well across many instances behind a load balancer. Keep state in a database or cache, make handlers idempotent, and add graceful shutdown with http.Server.Shutdown so deployments do not drop requests. Use log/slog for structured logs, and expose metrics (latency percentiles, goroutine count, GC pause time) so you can see regressions. Since Go 1.21, profile-guided optimisation lets the compiler use a production CPU profile (default.pgo in the main package) to inline and optimise hot paths, often improving performance by a few percent with no code change.
No. Write clear code, measure, and change only the parts the profile identifies. Unmeasured optimisations often add complexity without any gain.
No. It helps only for frequently allocated, reusable objects, and it adds overhead and complexity otherwise. Verify with a benchmark that shows fewer allocations and lower time.
For CPU-bound work, about one per core. For I/O-bound work, more is fine, but set an explicit limit based on what downstream systems can take.
Compare heap profiles taken at different times with go tool pprof -base, and check the goroutine profile for goroutines that never exit.
Benchmark and profile before changing anything, then reduce allocations, pick better algorithms and bound your concurrency. Tune I/O and connection reuse, set GOMEMLIMIT in containers, and scale stateless instances horizontally with metrics in place so regressions show up quickly.