Skip to content

Commit

Permalink
slices: add sort benchmark for sorted strings
Browse files Browse the repository at this point in the history
For golang#60777

Change-Id: I424535ce6454156c61af2f299228630ee304d165
Reviewed-on: https://go-review.googlesource.com/c/go/+/503815
Reviewed-by: Keith Randall <[email protected]>
Run-TryBot: Eli Bendersky <[email protected]>
Reviewed-by: Keith Randall <[email protected]>
Reviewed-by: Eli Bendersky <[email protected]>
TryBot-Result: Gopher Robot <[email protected]>
  • Loading branch information
eliben authored and eric committed Sep 7, 2023
1 parent e1346f6 commit ed41c2a
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/slices/sort_benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"math/rand"
"sort"
"strconv"
"strings"
"testing"
)
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand All @@ -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 {
Expand Down

0 comments on commit ed41c2a

Please sign in to comment.