| name | go-performance |
| description | Go performance optimization - profiling, benchmarks, memory management |
| sasmp_version | 1.3.0 |
| bonded_agent | 02-go-concurrency |
| bond_type | SECONDARY_BOND |
Go Performance Skill
Optimize Go application performance with profiling and best practices.
Overview
Comprehensive performance optimization including CPU/memory profiling, benchmarking, and common optimization patterns.
Parameters
| Parameter | Type | Required | Default | Description |
|---|
| profile_type | string | yes | - | Type: "cpu", "memory", "goroutine", "block" |
| duration | string | no | "30s" | Profile duration |
Core Topics
pprof Setup
import (
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
http.ListenAndServe("localhost:6060", nil)
}()
runApp()
}
CPU Profiling
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
(pprof) top 10
(pprof) list funcName
(pprof) web
(pprof) svg > cpu.svg
Memory Profiling
go tool pprof http://localhost:6060/debug/pprof/heap
go tool pprof http://localhost:6060/debug/pprof/allocs
(pprof) top --cum
(pprof) list funcName
Benchmarking
func BenchmarkProcess(b *testing.B) {
data := setupData()
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
Process(data)
}
}
func BenchmarkProcess_Parallel(b *testing.B) {
data := setupData()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
Process(data)
}
})
}
go test -bench=. -benchmem ./...
go test -bench=. -count=5 > old.txt
go test -bench=. -count=5 > new.txt
benchstat old.txt new.txt
Memory Optimization
func ProcessItems(items []Item) []Result {
results := make([]Result, 0, len(items))
for _, item := range items {
results = append(results, process(item))
}
return results
}
var bufferPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
func GetBuffer() *bytes.Buffer {
buf := bufferPool.Get().(*bytes.Buffer)
buf.Reset()
return buf
}
func PutBuffer(buf *bytes.Buffer) {
bufferPool.Put(buf)
}
Escape Analysis
go build -gcflags="-m -m" ./...
Optimization Patterns
var b strings.Builder
for _, s := range parts {
b.WriteString(s)
}
result := b.String()
buffer := make([]byte, 1024)
for {
n, err := reader.Read(buffer)
}
Profiling Commands
go tool pprof http://localhost:6060/debug/pprof/goroutine
go tool pprof http://localhost:6060/debug/pprof/block
go tool pprof http://localhost:6060/debug/pprof/mutex
curl -o trace.out http://localhost:6060/debug/pprof/trace?seconds=5
go tool trace trace.out
Troubleshooting
Failure Modes
| Symptom | Cause | Fix |
|---|
| High CPU | Hot loop, GC | Profile, reduce allocs |
| High memory | Leak, no pooling | Heap profile, sync.Pool |
| Slow start | Large init | Lazy initialization |
| GC pauses | Many allocations | Reduce allocations |
Usage
Skill("go-performance")