文章目录
参考 Go in Action
标准库提供了三种方法可以将整数值转为字符串。
- fmt.Sprintf
- strconv.FormatInt
- strconv.Itoa
运行下面的代码,可以得到三种方法的基础测试结果。
package test
import (
"fmt"
"strconv"
"testing"
)
func BenchmarkSprintf(b *testing.B) {
number := 10
b.ResetTimer()
for i := 0; i < b.N; i++ {
fmt.Sprintf("%d", number)
}
}
func BenchmarkFormat(b *testing.B) {
number := int64(10)
b.ResetTimer()
for i := 0; i < b.N; i++ {
strconv.FormatInt(number, 10)
}
}
func BenchmarkItoa(b *testing.B) {
number := 10
b.ResetTimer()
for i := 0; i < b.N; i++ {
strconv.Itoa(number)
}
}
测试结果如下。首先执行文件必须是 *_test.go 后缀的文件,然后通过 go test
来运行。从下面的结果可以看出,fmt.Sprintf
效率是最低的。
# ls
test_test.go
# go test -v -run="none" -bench=. -benchtime="3s" -benchmem
goos: darwin
goarch: amd64
BenchmarkSprintf-12 50000000 79.5 ns/op 16 B/op 2 allocs/op
BenchmarkFormat-12 2000000000 2.75 ns/op 0 B/op 0 allocs/op
BenchmarkItoa-12 2000000000 2.65 ns/op 0 B/op 0 allocs/op
PASS
ok _/tmp/test 15.408s