目录

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

概述

关于 Go 语言整数值转字符串的效率问题,用户必须清楚的一个小细节。

正文

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

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

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

 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
28
29
30
31
32
33
34
35
36
37
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 效率是最低的。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# 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

参考资料

  1. go-in-action
警告
本文最后更新于 2017年2月1日,文中内容可能已过时,请谨慎参考。