Go 性能优化
pprof 性能分析
Section titled “pprof 性能分析”import _ "net/http/pprof"
func main() { go func() { http.ListenAndServe("localhost:6060", nil) }() // 业务代码...}命令行分析:
# CPU 分析go tool pprof http://localhost:6060/debug/pprof/profile
# 内存分析go tool pprof http://localhost:6060/debug/pprof/heap
# 在浏览器中查看go tool pprof -http=:8080 cpu.proffunc BenchmarkFib(b *testing.B) { for i := 0; i < b.N; i++ { Fib(30) }}go test -bench=. -benchmem常见优化技巧
Section titled “常见优化技巧”1. 减少内存分配
Section titled “1. 减少内存分配”// ❌ 每次循环分配for i := 0; i < 1000; i++ { buf := make([]byte, 1024) process(buf)}
// ✅ 复用 bufferbuf := make([]byte, 1024)for i := 0; i < 1000; i++ { process(buf)}2. sync.Pool 对象复用
Section titled “2. sync.Pool 对象复用”var pool = sync.Pool{ New: func() interface{} { return make([]byte, 1024) },}
buf := pool.Get().([]byte)// 使用 buf...pool.Put(buf)3. 字符串拼接
Section titled “3. 字符串拼接”// ❌ 频繁分配s := ""for _, v := range parts { s += v}
// ✅ strings.Buildervar b strings.Builderfor _, v := range parts { b.WriteString(v)}s := b.String()4. 避免逃逸
Section titled “4. 避免逃逸”// ❌ 逃逸到堆func newPoint() *Point { return &Point{1, 2}}
// ✅ 栈分配func newPoint() Point { return Point{1, 2}}