在 Linux 上优化 Go(Golang)程序性能,通常可以从 语言层面、运行时、系统层面、工具链 四个维度来做。下面给你一个比较系统、可落地的优化清单。
make / newsync.Poolbuf := make([]byte, 0, 1024)
m := make(map[string]int, 100)
GOGC=50 ./app # 更激进 GC(减少内存,但 CPU 增加)
sem := make(chan struct{}, 100)
string ↔ []byte 频繁转换strings.Builder 代替 +bufioLinux 上通常:
GOMAXPROCS=物理核数
(Go 1.21+ 默认已合理)
GODEBUG=gctrace=1GODEBUG=schedtrace=1000runtime.LockOSThreadulimit -n 1000000
Go 网络服务常见瓶颈
net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
taskset -c 0-7 ./app
epoll(Go net 已用)import _ "net/http/pprof"
go tool pprof http://localhost:6060/debug/pprof/profile
看:
trace.Start(f)
defer trace.Stop()
go tool trace trace.out
go test -bench=. -benchmem
top / htopperfstracesar| 问题 | 原因 | 解决 |
|---|---|---|
| CPU 高 | 锁竞争 / 分配多 | pprof + sync.Pool |
| 内存高 | heap 大 | GOGC / 对象复用 |
| QPS 低 | IO 阻塞 | 异步 / 批处理 |
| 延迟抖动 | GC | 减少分配 |
| goroutine 爆炸 | 无限制并发 | worker pool |
如果你愿意,可以告诉我:
我可以直接给你针对性优化方案或代码示例。