@@ -7,6 +7,7 @@ package slices
7
7
import (
8
8
"math/rand"
9
9
"sort"
10
+ "strings"
10
11
"testing"
11
12
)
12
13
@@ -32,7 +33,7 @@ func BenchmarkSortInts(b *testing.B) {
32
33
}
33
34
}
34
35
35
- func BenchmarkSlicesSort (b * testing.B ) {
36
+ func BenchmarkSlicesSortInts (b * testing.B ) {
36
37
for i := 0 ; i < b .N ; i ++ {
37
38
b .StopTimer ()
38
39
ints := makeRandomInts (N )
@@ -57,6 +58,57 @@ func TestIntSorts(t *testing.T) {
57
58
}
58
59
}
59
60
61
+ // The following is a benchmark for sorting strings.
62
+
63
+ // makeRandomStrings generates n random strings with alphabetic runes of
64
+ // varying lenghts.
65
+ func makeRandomStrings (n int ) []string {
66
+ rand .Seed (42 )
67
+ var letters = []rune ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" )
68
+ ss := make ([]string , n )
69
+ for i := 0 ; i < n ; i ++ {
70
+ var sb strings.Builder
71
+ slen := 2 + rand .Intn (50 )
72
+ for j := 0 ; j < slen ; j ++ {
73
+ sb .WriteRune (letters [rand .Intn (len (letters ))])
74
+ }
75
+ ss [i ] = sb .String ()
76
+ }
77
+ return ss
78
+ }
79
+
80
+ func TestStringSorts (t * testing.T ) {
81
+ ss := makeRandomStrings (200 )
82
+ ss2 := Clone (ss )
83
+
84
+ sort .Strings (ss )
85
+ Sort (ss2 )
86
+
87
+ for i := range ss {
88
+ if ss [i ] != ss2 [i ] {
89
+ t .Fatalf ("ss2 mismatch at %d; %s != %s" , i , ss [i ], ss2 [i ])
90
+ }
91
+ }
92
+ }
93
+
94
+ func BenchmarkSortStrings (b * testing.B ) {
95
+ for i := 0 ; i < b .N ; i ++ {
96
+ b .StopTimer ()
97
+ ss := makeRandomStrings (N )
98
+ b .StartTimer ()
99
+ sort .Strings (ss )
100
+ }
101
+ }
102
+
103
+ func BenchmarkSlicesSortStrings (b * testing.B ) {
104
+ for i := 0 ; i < b .N ; i ++ {
105
+ b .StopTimer ()
106
+ ss := makeRandomStrings (N )
107
+ b .StartTimer ()
108
+ Sort (ss )
109
+ }
110
+ }
111
+
60
112
// These benchmarks compare sorting a slice of structs with sort.Sort vs.
61
113
// slices.SortFunc.
62
114
type myStruct struct {
0 commit comments