From 5ffcadcdf47d6d5a474fd6c78470987ff4480058 Mon Sep 17 00:00:00 2001 From: Pavel Kalinnikov Date: Tue, 27 Feb 2024 21:51:52 +0000 Subject: [PATCH] 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 16 elements. Signed-off-by: Pavel Kalinnikov --- quorum/majority.go | 15 ++------------- tracker/tracker.go | 12 ++---------- 2 files changed, 4 insertions(+), 23 deletions(-) diff --git a/quorum/majority.go b/quorum/majority.go index 12766137..0c9c24ee 100644 --- a/quorum/majority.go +++ b/quorum/majority.go @@ -17,6 +17,7 @@ package quorum import ( "fmt" "math" + "slices" "sort" "strings" ) @@ -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 { @@ -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 diff --git a/tracker/tracker.go b/tracker/tracker.go index 2710a7a4..5c4e14ce 100644 --- a/tracker/tracker.go +++ b/tracker/tracker.go @@ -16,6 +16,7 @@ package tracker import ( "fmt" + "slices" "sort" "strings" @@ -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) @@ -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]) }