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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
package main
import (
"bytes"
"fmt"
"strings"
"testing"
)
// 大量字符串拼接性能测试
// fmt.Printf
func BenchmarkFmtSprintfMore(b *testing.B) {
var s string
for i := 0; i < b.N; i++ {
s += fmt.Sprintf("%s%s", "hello", "world")
}
fmt.Errorf(s)
}
// 加号 拼接
func BenchmarkAddMore(b *testing.B) {
var s string
for i := 0; i < b.N; i++ {
s += "hello" + "world"
}
fmt.Errorf(s)
}
// strings.Join
func BenchmarkStringsJoinMore(b *testing.B) {
var s string
for i := 0; i < b.N; i++ {
s += strings.Join([]string{"hello", "world"}, "")
}
fmt.Errorf(s)
}
// bytes.Buffer
func BenchmarkBufferMore(b *testing.B) {
buffer := bytes.Buffer{}
for i := 0; i < b.N; i++ {
buffer.WriteString("hello")
buffer.WriteString("world")
}
fmt.Errorf(buffer.String())
}
// 单次字符串拼接性能测试
func BenchmarkFmtSprintf(b *testing.B) {
for i := 0; i < b.N; i++ {
s := fmt.Sprintf("%s%s", "hello", "world")
fmt.Errorf(s)
}
}
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
s := "hello" + "world"
fmt.Errorf(s)
}
}
func BenchmarkStringsJoin(b *testing.B) {
for i := 0; i < b.N; i++ {
s := strings.Join([]string{"hello", "world"}, "")
fmt.Errorf(s)
}
}
func BenchmarkBuffer(b *testing.B) {
for i := 0; i < b.N; i++ {
b := bytes.Buffer{}
b.WriteString("hello")
b.WriteString("world")
fmt.Errorf(b.String())
}
}
|