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

时间:2022-07-22
本文章向大家介绍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