基本数据类型与字符串之间的转换,优先使用 strconv 而不是 fmt,因为前者性能更佳。

Go 高性能编程技法 - 知乎 https://zhuanlan.zhihu.com/p/482547957

1.1 优先使用 strconv 而不是 fmt

基本数据类型与字符串之间的转换,优先使用 strconv 而不是 fmt,因为前者性能更佳。

// Bad
for i := 0; i < b.N; i++ {
 s := fmt.Sprint(rand.Int())
}

BenchmarkFmtSprint-4    143 ns/op    2 allocs/op

// Good
for i := 0; i < b.N; i++ {
 s := strconv.Itoa(rand.Int())
}

BenchmarkStrconv-4    64.2 ns/op    1 allocs/op

为什么性能上会有两倍多的差距,因为 fmt 实现上利用反射来达到范型的效果,在运行时进行类型的动态判断,所以带来了一定的性能损耗。

 

posted @ 2022-05-11 11:19  papering  阅读(78)  评论(0编辑  收藏  举报