Go学习笔记(day5) | 青训营笔记

51 阅读3分钟

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

笨人纯小白,笔记包括一些上课学到的知识和课外总结的内容,如有错误请指正!

七、Golang高质量编程

  1. 边界条件考虑完备
  2. 异常处理
  3. 易读易维护
  4. 规范编码:格式化代码格式
  5. 注释:解释作用,返回值,或者是报错原因
  6. 命名:
    • 缩略词大写,变量不需要导出时全小写
    • 作用域小的变量名尽量简洁
    • 作用域广的变量,或是函数的形参命名要有上下文信息
    • 函数名不要携带包名上下文信息
  7. 控制流程:
    • 冗余的else尽量省略
    • 尽量保持代码的最短缩进,例如:
    if err := doSomething(); err != nil {
        return err
    }
  1. 错误判定与输出日志: 不建议业务代码中使用panic,尽量使用error

八、Golang性能优化

Go语言提供了benchmark工具

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

8.1 优化工具概述

切片

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
    }

字符串处理

拼接处理来看,stringbuilderbytebuffer要比“+”快很多

+”会重新开辟内存空间

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

空结构体

可以节省内存

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

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

实战练习

    git clone https://gitclone.com/github.com/wolfogre/go-pprof-practice

启动项目后键入网址:

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

界面如下: image.png cpu 打开命令行,键入:

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

得到: image.png 接下来,执行语句:top;得到: image.png

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

我们可以看到,eat函数最耗时,使用list Eat看看它有什么问题? image.png 原理是for循环占用时间过长;那我们把它注释掉

    func (t *Tiger) Eat() {
        log.Println(t.Name(), "eat")
        // loop := 10000000000
        // for i := 0; i < loop; i++ {
        //  // do nothing
        // }
    }

再来看看top结果:没有刚才那么长了; image.png 使用命令web即可视化,需安装graphviz并配置path

堆内存

键入命令:

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

发现这个mouse.steal占用内存真的是高 image.png 继续注释掉:

    func (m *Mouse) steal() {
        log.Println(m.Name(), "steal")
        // max := constant.Gi
        // for len(m.buffer) * constant.Mi < max {
        // m.buffer = append(m.buffer, [constant.Mi]byte{})
        // }
    }

协程

    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"