服务器之家

服务器之家 > 正文

基于Go Int转string几种方式性能测试

时间:2021-06-06 01:12     来源/作者:贤冰

Go语言内置int转string至少有3种方式:

?
1
2
3
fmt.Sprintf("%d",n)
strconv.Itoa(n)
strconv.FormatInt(n,10)

下面针对这3中方式的性能做一下简单的测试:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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

执行:

?
1
go test -v -bench=. int2string_test.go -benchmem
?
1
2
3
4
5
6
7
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类型转换, 整型转换成字符串,字符串转换成整型

看代码吧~

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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))
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/flyfreelyit/article/details/79701577

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部