slices: add sort benchmark for sorted strings

For #60777

Change-Id: I424535ce6454156c61af2f299228630ee304d165
Reviewed-on: https://go-review.googlesource.com/c/go/+/503815
Reviewed-by: Keith Randall <khr@google.com>
Run-TryBot: Eli Bendersky <eliben@google.com>
Reviewed-by: Keith Randall <khr@golang.org>
Reviewed-by: Eli Bendersky <eliben@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
This commit is contained in:
Eli Bendersky
2023-06-15 09:34:22 -07:00
committed by Eli Bendersky
parent b7e7467865
commit f6e0dcc474

View File

@@ -8,6 +8,7 @@ import (
"fmt"
"math/rand"
"sort"
"strconv"
"strings"
"testing"
)
@@ -50,6 +51,15 @@ func BenchmarkSortInts(b *testing.B) {
}
}
func makeSortedStrings(n int) []string {
x := make([]string, n)
for i := 0; i < n; i++ {
x[i] = strconv.Itoa(i)
}
Sort(x)
return x
}
func BenchmarkSlicesSortInts(b *testing.B) {
for i := 0; i < b.N; i++ {
b.StopTimer()
@@ -153,6 +163,15 @@ func BenchmarkSortStrings(b *testing.B) {
}
}
func BenchmarkSortStrings_Sorted(b *testing.B) {
ss := makeSortedStrings(N)
b.ResetTimer()
for i := 0; i < b.N; i++ {
sort.Strings(ss)
}
}
func BenchmarkSlicesSortStrings(b *testing.B) {
for i := 0; i < b.N; i++ {
b.StopTimer()
@@ -162,6 +181,15 @@ func BenchmarkSlicesSortStrings(b *testing.B) {
}
}
func BenchmarkSlicesSortStrings_Sorted(b *testing.B) {
ss := makeSortedStrings(N)
b.ResetTimer()
for i := 0; i < b.N; i++ {
Sort(ss)
}
}
// These benchmarks compare sorting a slice of structs with sort.Sort vs.
// slices.SortFunc.
type myStruct struct {