# 构建时使用优化标志
go build -gcflags="-m -l" -ldflags="-s -w" your_package.go
# -gcflags="-m" 显示编译器优化决策
# -ldflags="-s -w" 减小二进制体积
// 在程序启动时设置GC参数
func init() {
// 设置GC目标百分比(默认100)
debug.SetGCPercent(200)
// 或使用环境变量
// GODEBUG=gctrace=1,gcpacertrace=1
}
// 使用worker池模式
type Task struct {
// 任务定义
}
func worker(id int, tasks <-chan Task, results chan<- Result) {
for task := range tasks {
// 处理任务
results <- process(task)
}
}
func main() {
numWorkers := runtime.NumCPU() * 2
tasks := make(chan Task, 100)
results := make(chan Result, 100)
// 启动worker
for i := 0; i < numWorkers; i++ {
go worker(i, tasks, results)
}
// 分发任务和收集结果
}
sync.RWMutex
sync/atomic
或无锁数据结构// 使用sync.Pool减少内存分配
var bufferPool = sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 0, 1024))
},
}
func getBuffer() *bytes.Buffer {
return bufferPool.Get().(*bytes.Buffer)
}
func putBuffer(buf *bytes.Buffer) {
buf.Reset()
bufferPool.Put(buf)
}
// 避免指针逃逸到堆上
func process(data []byte) []byte {
result := make([]byte, len(data)) // 尽量在栈上分配
// 处理数据
return result
}
// 数据局部性优化
type Data struct {
values []int64
padding [cacheLineSize - len([]int64)%cacheLineSize]byte
}
const cacheLineSize = 64 // 现代CPU缓存行大小
// 使用SIMD指令(通过汇编或专用库)
import "github.com/klauspost/cpuid/v2"
func init() {
if cpuid.CPU.Supports(cpuid.AVX2) {
// 使用AVX2优化版本
} else {
// 使用通用版本
}
}
# CPU分析
go test -cpuprofile cpu.prof -bench .
go tool pprof cpu.prof
# 内存分析
go test -memprofile mem.prof -bench .
go tool pprof -alloc_space mem.prof
# 火焰图生成
go-torch -u http://localhost:8080/debug/pprof/profile
# 提高文件描述符限制
ulimit -n 100000
# 调整内核参数
echo 1 > /proc/sys/net/ipv4/tcp_tw_reuse
echo 1 > /proc/sys/net/ipv4/tcp_fin_timeout
// 使用标准库的http连接池
client := &http.Client{
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 50,
IdleConnTimeout: 90 * time.Second,
},
Timeout: 10 * time.Second,
}
// 使用io.CopyBuffer减少内存拷贝
buf := make([]byte, 32*1024) // 32KB缓冲区
_, err := io.CopyBuffer(dst, src, buf)
# 多阶段构建减小镜像大小
FROM golang:1.19 as builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
FROM alpine:latest
WORKDIR /root/
COPY --from=builder /app/app .
CMD ["./app"]
// 使用syscall绕过标准库
fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)
// 高性能场景下的系统调用
记住:优化前先测量,使用pprof等工具确定瓶颈,避免过早优化。每种优化策略都需要根据具体应用场景进行测试和调整。