Go語言內置int轉string至少有3種方式:
fmt.Sprintf("%d",n)
strconv.Itoa(n)
strconv.FormatInt(n,10)
下面針對這3中方式的性能做一下簡單的測試:
package gotest
import (
"fmt"
"strconv"
"testing"
)
func BenchmarkSprintf(b *testing.B) {
n := 10
b.ResetTimer()
for i := 0; i b.N; i++ {
fmt.Sprintf("%d", n)
}
}
func BenchmarkItoa(b *testing.B) {
n := 10
b.ResetTimer()
for i := 0; i b.N; i++ {
strconv.Itoa(n)
}
}
func BenchmarkFormatInt(b *testing.B) {
n := int64(10)
b.ResetTimer()
for i := 0; i b.N; i++ {
strconv.FormatInt(n, 10)
}
}
保存文件為int2string_test.go
執(zhí)行:
go test -v -bench=. int2string_test.go -benchmem
goos: darwin
goarch: amd64
BenchmarkSprintf-8 20000000 114 ns/op 16 B/op 2 allocs/op
BenchmarkItoa-8 200000000 6.33 ns/op 0 B/op 0 allocs/op
BenchmarkFormatInt-8 300000000 4.10 ns/op 0 B/op 0 allocs/op
PASS
ok command-line-arguments 5.998s
總體來說,strconv.FormatInt()效率最高,fmt.Sprintf()效率最低
補充:Golang類型轉換, 整型轉換成字符串,字符串轉換成整型
看代碼吧~
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
//字符串轉成整型int
num,err:=strconv.Atoi("123")
if err!=nil {
panic(err)
}
fmt.Println(num,reflect.TypeOf(num))
//整型轉換成字符串
str:=strconv.Itoa(123)
fmt.Println(str,reflect.TypeOf(str))
}
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- Golang 空map和未初始化map的注意事項說明
- Golang 如何判斷數組某個元素是否存在 (isset)
- golang 函數返回chan類型的操作
- Go語言的Channel遍歷方法詳解
- Golang 拷貝Array或Slice的操作
- Go語言中break label與goto label的區(qū)別
- Go 實現英尺和米的簡單單位換算方式