-
Notifications
You must be signed in to change notification settings - Fork 1
/
strconcat_test.go
72 lines (62 loc) · 1.3 KB
/
strconcat_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
package bench_test
import (
"bytes"
"fmt"
"strings"
"testing"
)
func BenchmarkStringConcat_Literal(b *testing.B) {
lines := make([]string, 1000)
for i := 0; i < len(lines); i++ {
lines[i] = fmt.Sprintf("Hello... World... #%d !!!", i)
}
concat := func(s []string) string {
var temp string
for i := 0; i < len(s); i++ {
temp += s[i]
}
return temp
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = concat(lines)
}
}
func BenchmarkStringConcat_BytesBuffer(b *testing.B) {
lines := make([]string, 1000)
for i := 0; i < len(lines); i++ {
lines[i] = fmt.Sprintf("Hello... World... #%d !!!", i)
}
concat := func(s []string) string {
var bb bytes.Buffer
for i := 0; i < len(s); i++ {
if _, err := bb.WriteString(s[i]); err != nil {
panic(err)
}
}
return bb.String()
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = concat(lines)
}
}
func BenchmarkStringConcat_StringBuilder(b *testing.B) {
lines := make([]string, 1000)
for i := 0; i < len(lines); i++ {
lines[i] = fmt.Sprintf("Hello... World... #%d !!!", i)
}
concat := func(s []string) string {
var sb strings.Builder
for i := 0; i < len(s); i++ {
if _, err := sb.WriteString(s[i]); err != nil {
panic(err)
}
}
return sb.String()
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = concat(lines)
}
}