- 数字转换成字符串,使用 strconv.Itoa() 比 fmt.Sprintf() 要快
func BenchmarkItoa(b *testing.B) {
number := 1234567890
b.ResetTimer()
for i := 0; i < b.N; i++ {
strconv.Itoa(number)
}
}
func BenchmarkSprint(b *testing.B) {
number := 1234567890
b.ResetTimer()
for i := 0; i < b.N; i++ {
fmt.Sprint(number)
}
}
结果
goos: windows
goarch: amd64
pkg: test/one
BenchmarkItoa
BenchmarkItoa-12 33422924 34.5 ns/op
BenchmarkSprint
BenchmarkSprint-12 13076952 91.3 ns/op
对比一下源码
func FormatInt(i int64, base int) string {
if fastSmalls && 0 <= i && i < nSmalls && base == 10 {
return small(int(i))
}
_, s := formatBits(nil, uint64(i), base, i < 0, false)
return s
}
func small(i int) string {
if i < 10 {
return digi