基于Go Int轉(zhuǎn)string幾種方式性能測(cè)試
更新時(shí)間:2021年04月28日 16:43:52 作者:賢冰
這篇文章主要介紹了Go Int轉(zhuǎn)string幾種方式測(cè)試,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
Go語(yǔ)言內(nèi)置int轉(zhuǎn)string至少有3種方式:
fmt.Sprintf("%d",n) strconv.Itoa(n) strconv.FormatInt(n,10)
下面針對(duì)這3中方式的性能做一下簡(jiǎn)單的測(cè)試:
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
總體來(lái)說(shuō),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語(yǔ)言編程中slice切片結(jié)構(gòu)
這篇文章主要介紹了Go語(yǔ)言編程中slice切片結(jié)構(gòu),其中Append方法的用法介紹較為詳細(xì),需要的朋友可以參考下2015-10-10Go 語(yǔ)言 JSON 標(biāo)準(zhǔn)庫(kù)的使用
今天通過(guò)本文給大家介紹Go 語(yǔ)言 JSON 標(biāo)準(zhǔn)庫(kù)的使用小結(jié),包括序列化和反序列化的相關(guān)知識(shí),感興趣的朋友跟隨小編一起看看吧2021-10-10