GoFrame 框架培训大纲 - 第11章:性能优化
11.1 代码优化
11.1.1 性能分析工具
- pprof性能分析
package main
import (
"log"
"net/http"
_ "net/http/pprof"
"runtime"
)
func main() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
performanceIntensiveTask()
}
func performanceIntensiveTask() {
defer profile.Start(profile.CPUProfile, profile.ProfilePath(".")).Stop()
defer profile.Start(profile.MemProfile, profile.ProfilePath(".")).Stop()
}
- 性能追踪
func tracePerformance() {
f, err := os.Create("trace.out")
if err != nil {
log.Fatal(err)
}
defer f.Close()
err = trace.Start(f)
if err != nil {
log.Fatal(err)
}
defer trace.Stop()
complexCalculation()
}
11.1.2 常见性能问题与优化
- 内存分配优化
func inefficientStringConcat(items []string) string {
var result string
for _, item :=