What Is PGO (Profile-Guided Optimization) in Go and How to Use It

PGO in Go optimizes code by using runtime profiling data to devirtualize calls and inline hot functions, requiring a profile generation step followed by a rebuild with the `-pgo` flag.

Profile-Guided Optimization (PGO) in Go uses runtime execution data to optimize hot code paths, primarily by devirtualizing interface calls and enabling aggressive inlining. To use it, run your application with profiling enabled, then rebuild using the generated profile data.

# 1. Generate profile data by running your app
export GOCACHE=$(mktemp -d)
go build -gcflags="all=-m=2" -o myapp .
./myapp > /dev/null

# 2. Rebuild with PGO using the generated profile
# (Note: In current Go versions, PGO is often enabled via -pgo flag if profile exists)
go build -pgo=profile.pb.gz -o myapp_optimized .

Note: The -pgo flag and profile.pb.gz filename depend on your specific Go version and how the profile was generated (e.g., via go test -bench or runtime/pprof).