Dong.Ge

左手代码 右手江湖

golang 字符串连接+和sprintf比较

东哥's Avatar 2019-08-16

项目组两个人都说 字符串拼接 sprintf比+号效率高,就自己试了下

结果并不是他们说的

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
38
39
40
41
42
package main

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

func BenchmarkPlus(b *testing.B) {
var wcd string
for i := 0; i < b.N; i++ {
wcd = "vip:" + "123456789" + "999999999"
}
_ = wcd
}

func BenchmarkSprintf(b *testing.B) {
var wcd string
for i := 0; i < b.N; i++ {
wcd = fmt.Sprintf("%s%s%s", "vip:", "123456789", "999999999")
}
_ = wcd
}

func BenchmarkPlusWithInt2str(b *testing.B) {
var wcd string
for i := 0; i < b.N; i++ {
wcd = "vip:" + "123456789" + strconv.Itoa(999999999)
}
_ = wcd
}

func BenchmarkSprintfWithInt2str(b *testing.B) {
var wcd string
for i := 0; i < b.N; i++ {
wcd = fmt.Sprintf("%s%s%d", "vip:", "123456789", 999999999)
}
_ = wcd
}

//go test -bench=. plus_vs_sprintf_test.go
//go test -v -bench=".*Int2str" plus_vs_sprintf_test.go
1
2
3
4
5
6
7
8
goos: darwin
goarch: amd64
BenchmarkPlus-8 2000000000 0.32 ns/op
BenchmarkSprintf-8 10000000 147 ns/op
BenchmarkPlusWithInt2str-8 20000000 94.6 ns/op
BenchmarkSprintfWithInt2str-8 10000000 169 ns/op
PASS
ok command-line-arguments 6.185s
本文最后更新于 天前,文中所描述的信息可能已发生改变