Skip to content

Commit aaef6db

Browse files
committed
slices: add benchmarks for sorting strings
Change-Id: I878dc782bd0cae87577800e9ee2843668bfdea12 Reviewed-on: https://go-review.googlesource.com/c/exp/+/394135 Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Trust: Eli Bendersky‎ <[email protected]>
1 parent 2d6d886 commit aaef6db

File tree

1 file changed

+53
-1
lines changed

1 file changed

+53
-1
lines changed

slices/sort_benchmark_test.go

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package slices
77
import (
88
"math/rand"
99
"sort"
10+
"strings"
1011
"testing"
1112
)
1213

@@ -32,7 +33,7 @@ func BenchmarkSortInts(b *testing.B) {
3233
}
3334
}
3435

35-
func BenchmarkSlicesSort(b *testing.B) {
36+
func BenchmarkSlicesSortInts(b *testing.B) {
3637
for i := 0; i < b.N; i++ {
3738
b.StopTimer()
3839
ints := makeRandomInts(N)
@@ -57,6 +58,57 @@ func TestIntSorts(t *testing.T) {
5758
}
5859
}
5960

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+
60112
// These benchmarks compare sorting a slice of structs with sort.Sort vs.
61113
// slices.SortFunc.
62114
type myStruct struct {

0 commit comments

Comments
 (0)