Skip to content

Commit 1f9cb53

Browse files
committed
tracker,quorum: use native Sort
The insertion sort is no longer needed, since Go 1.21 introduced a generic slices.Sort algorithm which achieves the same effect: it doesn't incur allocations, and uses insertion sort for slices up to 12 elements. Signed-off-by: Pavel Kalinnikov <pavel@cockroachlabs.com>
1 parent d475d7e commit 1f9cb53

File tree

2 files changed

+4
-23
lines changed

2 files changed

+4
-23
lines changed

quorum/majority.go

+2-13
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ package quorum
1717
import (
1818
"fmt"
1919
"math"
20+
"slices"
2021
"sort"
2122
"strings"
2223
)
@@ -112,15 +113,6 @@ func (c MajorityConfig) Slice() []uint64 {
112113
return sl
113114
}
114115

115-
func insertionSort(sl []uint64) {
116-
a, b := 0, len(sl)
117-
for i := a + 1; i < b; i++ {
118-
for j := i; j > a && sl[j] < sl[j-1]; j-- {
119-
sl[j], sl[j-1] = sl[j-1], sl[j]
120-
}
121-
}
122-
}
123-
124116
// CommittedIndex computes the committed index from those supplied via the
125117
// provided AckedIndexer (for the active config).
126118
func (c MajorityConfig) CommittedIndex(l AckedIndexer) Index {
@@ -159,10 +151,7 @@ func (c MajorityConfig) CommittedIndex(l AckedIndexer) Index {
159151
}
160152
}
161153
}
162-
163-
// Sort by index. Use a bespoke algorithm (copied from the stdlib's sort
164-
// package) to keep srt on the stack.
165-
insertionSort(srt)
154+
slices.Sort(srt)
166155

167156
// The smallest index into the array for which the value is acked by a
168157
// quorum. In other words, from the end of the slice, move n/2+1 to the

tracker/tracker.go

+2-10
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ package tracker
1616

1717
import (
1818
"fmt"
19+
"slices"
1920
"sort"
2021
"strings"
2122

@@ -180,15 +181,6 @@ func (p *ProgressTracker) Committed() uint64 {
180181
return uint64(p.Voters.CommittedIndex(matchAckIndexer(p.Progress)))
181182
}
182183

183-
func insertionSort(sl []uint64) {
184-
a, b := 0, len(sl)
185-
for i := a + 1; i < b; i++ {
186-
for j := i; j > a && sl[j] < sl[j-1]; j-- {
187-
sl[j], sl[j-1] = sl[j-1], sl[j]
188-
}
189-
}
190-
}
191-
192184
// Visit invokes the supplied closure for all tracked progresses in stable order.
193185
func (p *ProgressTracker) Visit(f func(id uint64, pr *Progress)) {
194186
n := len(p.Progress)
@@ -206,7 +198,7 @@ func (p *ProgressTracker) Visit(f func(id uint64, pr *Progress)) {
206198
n--
207199
ids[n] = id
208200
}
209-
insertionSort(ids)
201+
slices.Sort(ids)
210202
for _, id := range ids {
211203
f(id, p.Progress[id])
212204
}

0 commit comments

Comments
 (0)