Skip to content

Commit

Permalink
tracker,quorum: use native Sort
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
pav-kv committed Feb 27, 2024
1 parent d475d7e commit 1f9cb53
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 23 deletions.
15 changes: 2 additions & 13 deletions quorum/majority.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package quorum
import (
"fmt"
"math"
"slices"
"sort"
"strings"
)
Expand Down Expand Up @@ -112,15 +113,6 @@ func (c MajorityConfig) Slice() []uint64 {
return sl
}

func insertionSort(sl []uint64) {
a, b := 0, len(sl)
for i := a + 1; i < b; i++ {
for j := i; j > a && sl[j] < sl[j-1]; j-- {
sl[j], sl[j-1] = sl[j-1], sl[j]
}
}
}

// CommittedIndex computes the committed index from those supplied via the
// provided AckedIndexer (for the active config).
func (c MajorityConfig) CommittedIndex(l AckedIndexer) Index {
Expand Down Expand Up @@ -159,10 +151,7 @@ func (c MajorityConfig) CommittedIndex(l AckedIndexer) Index {
}
}
}

// Sort by index. Use a bespoke algorithm (copied from the stdlib's sort
// package) to keep srt on the stack.
insertionSort(srt)
slices.Sort(srt)

// The smallest index into the array for which the value is acked by a
// quorum. In other words, from the end of the slice, move n/2+1 to the
Expand Down
12 changes: 2 additions & 10 deletions tracker/tracker.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package tracker

import (
"fmt"
"slices"
"sort"
"strings"

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

func insertionSort(sl []uint64) {
a, b := 0, len(sl)
for i := a + 1; i < b; i++ {
for j := i; j > a && sl[j] < sl[j-1]; j-- {
sl[j], sl[j-1] = sl[j-1], sl[j]
}
}
}

// Visit invokes the supplied closure for all tracked progresses in stable order.
func (p *ProgressTracker) Visit(f func(id uint64, pr *Progress)) {
n := len(p.Progress)
Expand All @@ -206,7 +198,7 @@ func (p *ProgressTracker) Visit(f func(id uint64, pr *Progress)) {
n--
ids[n] = id
}
insertionSort(ids)
slices.Sort(ids)
for _, id := range ids {
f(id, p.Progress[id])
}
Expand Down

0 comments on commit 1f9cb53

Please sign in to comment.