go 性能相关总结

性能测试基本概念

基本概念

Benchmark: 性能测试

ns/op: 纳秒/每个操作,前面数值越小越快

命令

  • go test -c
  • go test -test.bench=. -test.cpuprofile=cpu.prof
  • go tool pprof bench.test cpu.prof

示例

建立一个包,创建一个test文件如,文件名为lib_test.go

package lib

import (
	"testing"
	"fmt"
)

const (
	str = "hello gohpers!"
	sep = ","
)

func BenchmarkFmt(b *testing.B)  {
	for i := 0; i < b.N ; i++ {
		_ = fmt.Sprintf("%s%s%s%s%s", str, sep, str, sep, str)
	}
	
}

func BenchmarkPlus(b *testing.B)  {
	for i:=0; i < b.N; i++  {
		_ = str + sep + str + sep + str
	}
}


然后运行 go test -bench=. 后面这个参数"." 不能加引号

结果

// Benchmark 名字 - CPU            循环次数             平均每次执行时间 
BenchmarkFmt-4             	      3000000	             554 ns/op
BenchmarkPlus-4            	    2000000000	            0.36 ns/op

结论:  0.36 更快一点

一些优化小点

  1. 在for循环中, ++i要比i++快, for逐渐减小要比逐渐增加快

  2. 使用 "+" 比使用fmt.Sprintf() 快

  3. 使用 strconv 包转换 要比 fmt.Sprintf 快

  4. 使用 strings.Join() 比 "+" 快

  5. 使用string.Join() 比 bytes.Buffer() 快

  6. 指定cap的slice 比不指定的快,指定的cap的map比不指定的快。slice 要比使用map快。

string 和 []byte
  • 如果可以的话,尽量用多[]byte,少用string
  • 尽可能少地在两者之间做转换

后续继续补充

参考

Go 语言测试(Test)、性能测试(Benchmark) 学习笔记

PS: 觉得不错的请点个赞吧!! (ง •̀_•́)ง

转载于:https://my.oschina.net/solate/blog/793566

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值