主頁 > 知識庫 > 基于Go Int轉(zhuǎn)string幾種方式性能測試

基于Go Int轉(zhuǎn)string幾種方式性能測試

熱門標簽:電話機器人軟件免費 外呼系統(tǒng)用什么卡 外呼系統(tǒng)顯本地手機號 阿克蘇地圖標注 涿州代理外呼系統(tǒng) excel地圖標注分布數(shù)據(jù) 評價高的400電話辦理 百度地圖標注后傳給手機 壽光微信地圖標注

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()效率最低

補充: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))
}

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

您可能感興趣的文章:
  • Golang 空map和未初始化map的注意事項說明
  • Golang 如何判斷數(shù)組某個元素是否存在 (isset)
  • golang 函數(shù)返回chan類型的操作
  • Go語言的Channel遍歷方法詳解
  • Golang 拷貝Array或Slice的操作
  • Go語言中break label與goto label的區(qū)別
  • Go 實現(xiàn)英尺和米的簡單單位換算方式

標簽:吐魯番 欽州 蘭州 銅川 梅河口 雞西 重慶 汕頭

巨人網(wǎng)絡(luò)通訊聲明:本文標題《基于Go Int轉(zhuǎn)string幾種方式性能測試》,本文關(guān)鍵詞  基于,Int,轉(zhuǎn),string,幾種,方式,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《基于Go Int轉(zhuǎn)string幾種方式性能測試》相關(guān)的同類信息!
  • 本頁收集關(guān)于基于Go Int轉(zhuǎn)string幾種方式性能測試的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章