基于Go Int轉(zhuǎn)string幾種方式性能測試
更新時(shí)間:2021年04月28日 16:43:52 作者:賢冰
這篇文章主要介紹了Go Int轉(zhuǎn)string幾種方式測試,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
Go語言內(nèi)置int轉(zhuǎn)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()效率最低
補(bǔ)充:Golang類型轉(zhuǎn)換, 整型轉(zhuǎn)換成字符串,字符串轉(zhuǎn)換成整型
看代碼吧~
package main import ( "fmt" "reflect" "strconv" ) func main() { //字符串轉(zhuǎn)成整型int num,err:=strconv.Atoi("123") if err!=nil { panic(err) } fmt.Println(num,reflect.TypeOf(num)) //整型轉(zhuǎn)換成字符串 str:=strconv.Itoa(123) fmt.Println(str,reflect.TypeOf(str)) }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
深入解析Go語言編程中slice切片結(jié)構(gòu)
這篇文章主要介紹了Go語言編程中slice切片結(jié)構(gòu),其中Append方法的用法介紹較為詳細(xì),需要的朋友可以參考下2015-10-10