-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstrings_concat_test.go
101 lines (88 loc) · 2.24 KB
/
strings_concat_test.go
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"fmt"
"strings"
"sync"
"testing"
)
var Concat string
type concatBench func(first string, nops int) string
func BenchmarkConcat(b *testing.B) {
for _, stringSize := range sizes {
for _, nOperations := range sizes {
b.Run(
fmt.Sprintf("plus_sign(%d) ops:(%d)", stringSize, nOperations),
benchmarkConcat(stringSize, nOperations, concatPlus),
)
b.Run(
fmt.Sprintf("sprintf(%d) ops:(%d)", stringSize, nOperations),
benchmarkConcat(stringSize, nOperations, concatSprintf),
)
b.Run(
fmt.Sprintf("strings_join(%d) ops:(%d)", stringSize, nOperations),
benchmarkConcat(stringSize, nOperations, concatJoin),
)
b.Run(
fmt.Sprintf("strings_builder(%d) ops:(%d)", stringSize, nOperations),
benchmarkConcat(stringSize, nOperations, concatBuilder),
)
b.Run(
fmt.Sprintf("strings_builder_pool(%d) ops:(%d)", stringSize, nOperations),
benchmarkConcat(stringSize, nOperations, concatBuilderPool),
)
}
}
}
func benchmarkConcat(strSize, nOps int, runF concatBench) func(*testing.B) {
teststr := testingString(strSize)
return func(b *testing.B) {
var f string
for n := 0; n < b.N; n++ {
f = runF(teststr, nOps)
}
Concat = f
}
}
func concatPlus(teststr string, nOps int) string {
for i := 0; i < nOps; i++ {
teststr = teststr + "..."
}
return teststr
}
func concatSprintf(teststr string, nOps int) string {
for i := 0; i < nOps; i++ {
teststr = fmt.Sprintf("%s%s", teststr, "...")
}
return teststr
}
func concatJoin(teststr string, nOps int) string {
for i := 0; i < nOps; i++ {
teststr = strings.Join([]string{teststr, "..."}, "")
}
return teststr
}
func concatBuilder(teststr string, nOps int) string {
var builder strings.Builder
builder.Grow(len(teststr))
for i := 0; i < nOps; i++ {
builder.WriteString(teststr)
builder.WriteString("...")
}
return builder.String()
}
var builderPool = sync.Pool{
New: func() any {
return new(strings.Builder)
},
}
func concatBuilderPool(teststr string, nOps int) string {
builder := builderPool.Get().(*strings.Builder)
builder.Reset()
builder.Grow(len(teststr))
defer builderPool.Put(builder)
for i := 0; i < nOps; i++ {
builder.WriteString(teststr)
builder.WriteString("...")
}
return builder.String()
}