Go高质量编程与性能调优 | 青训营笔记

57 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第4天

1.高质量编程

边界条件考虑完备

异常处理

易读易维护

规范编码:

格式化代码格式

注释:解释作用,返回值,或是报错原因

命名:

缩略词大写,变量不需要导出时全小写

作用域小的变量命名尽量简洁

作用域广的变量,或是函数的形参命名要有上下文信息

函数名不要携带包名上下文信息

控制流程:

冗余的else尽量省略

尽量保持代码最短缩进,例如

if err := doSomething(); err != nil { return err }

错误判定与输出日志

不建议业务代码中使用panic,尽量使用error

2.性能优化

Go语言提供了benchmark工具

执行语句为 go test -bench=. -benchmem

切片

slice预先分配 data := make([]type, 0, size),不声明size会导致append时不断扩容

map也是同理

在大切片上截取时,使用copy要比在切片上进行切片操作占用内存小的多

//占用内存大 fun do1(origin []int) []int { return origin[len(origin) - 2:] }

//占用内存小 fun do2(origin []int) []int { res = make([]int, 2) copy(res, origin[len(origin) - 2:]) return res } 字符串处理

拼接处理来看, stringbuilder, bytebuffer 要比 + 快很多

+会重新开辟内存空间

stringbuilder, bytebuffer底层都是[]byte数组

空结构体

可以节省内存

3. 性能分析工具pprof(p-prof)

具体可参考golang pprof 实战 | Wolfogre's Blog

帮助了解消耗了多少cpu,memory,支持可视化与性能分析

实战练习

git clone gitclone.com/github.com/… 启动项目后键入网址:

http://localhost:6060/debug/pprof/

打开命令行,键入

go tool pprof "http://localhost:6060/debug/pprof/profile?second=10"

接下来,执行语句top得到

flat:运行耗时 cum : 调用其他+运行总耗时

flat%:运行占用cpu百分比 cum%: 调用其他+运行占用cpu百分比

我们可以看到,eat函数最耗时,看看他有什么问题?

list Eat

原理是for循环占用时间过长 那我们把他注释掉 再来看看top结果

没有刚才那么长了

使用命令web即可可视化,需安装graphviz并配置path

堆内存

键入命令

go tool pprof -http=:8080 "http://localhost:6060/debug/pprof/heap"

发现这个mouse.steal占用内存真的是高

协程

go tool pprof -http=:8080 "http://localhost:6060/debug/pprof/goroutine" 火焰图是动态的

go tool pprof -http=:8080 "http://localhost:6060/debug/pprof/mutex"

阻塞

go tool pprof -http=:8080 "http://localhost:6060/debug/pprof/block"