Go语言整数值转字符串的效率问题

文章目录

参考 Go in Action

标准库提供了三种方法可以将整数值转为字符串。

  1. fmt.Sprintf
  2. strconv.FormatInt
  3. strconv.Itoa

运行下面的代码,可以得到三种方法的基础测试结果。

package test

import (
	"fmt"
	"strconv"
	"testing"
)

func BenchmarkSprintf(b *testing.B) {
	number := 10

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		fmt.Sprintf("%d", number)
	}
}

func BenchmarkFormat(b *testing.B) {
	number := int64(10)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		strconv.FormatInt(number, 10)
	}
}

func BenchmarkItoa(b *testing.B) {
	number := 10

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		strconv.Itoa(number)
	}
}

测试结果如下。首先执行文件必须是 *_test.go 后缀的文件,然后通过 go test 来运行。从下面的结果可以看出,fmt.Sprintf 效率是最低的。

# ls
test_test.go
# go test -v -run="none" -bench=. -benchtime="3s" -benchmem
goos: darwin
goarch: amd64
BenchmarkSprintf-12    	50000000	        79.5 ns/op	      16 B/op	       2 allocs/op
BenchmarkFormat-12     	2000000000	         2.75 ns/op	       0 B/op	       0 allocs/op
BenchmarkItoa-12       	2000000000	         2.65 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	_/tmp/test	15.408s
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值