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

Go语言内置int转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

执行:

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()效率最低
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值