Performance Tuning
Overview
Go provides built-in profiling tools for CPU, memory, and execution analysis.
Benchmarks
func BenchmarkFoo(b *testing.B) {
for i := 0; i < b.N; i++ {
Foo()
}
}go test -bench=. -benchmemCPU Profiling
go test -cpuprofile=cpu.out -bench=.
go tool pprof cpu.outpprof Commands
(pprof) top10 # Top functions
(pprof) list FuncName # Annotated source
(pprof) web # Visual graph
Memory Profiling
go test -memprofile=mem.out -bench=.
go tool pprof -alloc_space mem.outHTTP Profiling
import _ "net/http/pprof"
// Endpoints:
// /debug/pprof/
// /debug/pprof/heap
// /debug/pprof/goroutine
// /debug/pprof/profileTracing
go test -trace=trace.out
go tool trace trace.outOptimization Tips
Reduce Allocations
// Preallocate
s := make([]int, 0, expectedSize)
// Reuse with sync.Pool
var pool = sync.Pool{New: func() any { return &Buffer{} }}
// strings.Builder for concatenation
var b strings.BuilderAvoid Copying
// Pass pointer for large structs
func process(data *LargeStruct)
// Use slices instead of arrays
func process(data []byte)Summary
| Tool | Purpose |
|---|---|
go test -bench |
Benchmarking |
go tool pprof |
Profile analysis |
go tool trace |
Execution tracing |
-gcflags=-m |
Escape analysis |