fmt.Sprintf("%d",n) strconv.Itoa(n) strconv.FormatInt(n,10)
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
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類(lèi)型轉(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ò)誤或未考慮完全的地方,望不吝賜教。
標(biāo)簽:吐魯番 欽州 蘭州 銅川 梅河口 雞西 重慶 汕頭
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《基于Go Int轉(zhuǎn)string幾種方式性能測(cè)試》,本文關(guān)鍵詞 基于,Int,轉(zhuǎn),string,幾種,方式,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。