strconv.Atoi() 将ASCLL 字符串中的数字转换为整数.这是Go标准库的一个基本函数.因此它肯定是得到很好的编码.并且经过多次优化.这里我们折腾下还有什么方式能够有所改进. 纯粹因为研究Go的不同用法.
正文:
我们看下 strconv.Atoi()的基准测试:
func BenchmarkAtoi(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
strconv.Atoi("12")
}
}
假如你的项目里大多数数字都是 2字节长度或4字节长度的话.或许可以这样处理字符串数字:
// 字符串 len == 2 的情况
func atoi2(in string) (int, error) {
a, b := int(in[0]-'0'), int(in[1]-'0')
if a < 0 || a > 9 || b < 0 || b > 9 {
return 0, fmt.Errorf("can't parse number %q", in)
}
return a*10 + b, nil
}
// len == 4 的情况下
func atoi4(in string) (int, error) {
a, b, c, d := int(in[0]-'0'), int(in[1]-'0'), int(