Go 語言將 unit 類型轉成 string

本頁內容

Go 語言將 unit 類型轉成 string 的幾種方法和比較。

fmt.Sprint

1func sprint(u uint) string {
2    return fmt.Sprint(u)
3}

strconv.FormatUint

1func formatUint(u uint) string {
2    return strconv.FormatUint(uint64(u), 10)
3}

性能

 1func BenchmarkSprint(b *testing.B) {
 2    for n := 0; n < b.N; n++ {
 3        sprint(uint(n))
 4    }
 5}
 6
 7func BenchmarkFormatUint(b *testing.B) {
 8    for n := 0; n < b.N; n++ {
 9        formatUint(uint(n))
10    }
11}
1$ go test -bench=.
2BenchmarkSprint-12              13384656                81.6 ns/op
3BenchmarkFormatUint-12          44932880                29.5 ns/op

後者明顯性能更好。