Golang 数字转字符串性能对比
- 测试平台: M1 Macbook Pro
- golang版本: 1.18.3
测试代码
package number_string_conversion
import (
"fmt"
"strconv"
"testing"
)
const (
Int = 123456789
Float = 1.23456789
)
func BenchmarkForUseFmtInt(b *testing.B) {
for i := 0; i < b.N; i++ {
j := fmt.Sprint(Int)
_ = j
}
}
func BenchmarkForUseStrconvInt(b *testing.B) {
for i := 0; i < b.N; i++ {
j := strconv.Itoa(Int)
_ = j
}
}
func BenchmarkForUseFmtFloat(b *testing.B) {
for i := 0; i < b.N; i++ {
f := fmt.Sprintf("%.3f", Float)
_ = f
}
}
func BenchmarkForUseStrconvFloat(b *testing.B) {
for i := 0; i < b.N; i++ {
f := strconv.FormatFloat(Float, 'f', 3, 64)
_ = f
}
}
测试结果
go test -bench=. -benchmem -run=none
goos: darwin
goarch: arm64
pkg: golang_benchmark/number_string_conversion
BenchmarkForUseFmtInt-8 26354566 45.43 ns/op 16 B/op 1 allocs/op
BenchmarkForUseStrconvInt-8 56409640 21.40 ns/op 16 B/op 1 allocs/op
BenchmarkForUseFmtFloat-8 5879715 194.7 ns/op 5 B/op 1 allocs/op
BenchmarkForUseStrconvFloat-8 6860202 174.6 ns/op 29 B/op 2 allocs/op
PASS
ok golang_benchmark/number_string_conversion 6.340s
测试结论
- strconv包的性能明显优于fmt包