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=. -benchmem

CPU Profiling

go test -cpuprofile=cpu.out -bench=.
go tool pprof cpu.out

pprof 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.out

HTTP Profiling

import _ "net/http/pprof"

// Endpoints:
// /debug/pprof/
// /debug/pprof/heap
// /debug/pprof/goroutine
// /debug/pprof/profile

Tracing

go test -trace=trace.out
go tool trace trace.out

Optimization 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.Builder

Avoid 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