Merge pull request #125140 from huww98/sets-slices-sort

util/sets: simplify List() by using slices.Sort
This commit is contained in:
Kubernetes Prow Robot
2025-09-23 14:40:13 -07:00
committed by GitHub
2 changed files with 20 additions and 16 deletions

View File

@@ -18,7 +18,7 @@ package sets
import (
"cmp"
"sort"
"slices"
)
// Set is a set of the same type elements, implemented via map[comparable]struct{} for minimal memory consumption.
@@ -188,22 +188,13 @@ func (s1 Set[T]) Equal(s2 Set[T]) bool {
return len(s1) == len(s2) && s1.IsSuperset(s2)
}
type sortableSliceOfGeneric[T cmp.Ordered] []T
func (g sortableSliceOfGeneric[T]) Len() int { return len(g) }
func (g sortableSliceOfGeneric[T]) Less(i, j int) bool { return less[T](g[i], g[j]) }
func (g sortableSliceOfGeneric[T]) Swap(i, j int) { g[i], g[j] = g[j], g[i] }
// List returns the contents as a sorted T slice.
//
// This is a separate function and not a method because not all types supported
// by Generic are ordered and only those can be sorted.
func List[T cmp.Ordered](s Set[T]) []T {
res := make(sortableSliceOfGeneric[T], 0, len(s))
for key := range s {
res = append(res, key)
}
sort.Sort(res)
res := s.UnsortedList()
slices.Sort(res)
return res
}
@@ -230,7 +221,3 @@ func (s Set[T]) PopAny() (T, bool) {
func (s Set[T]) Len() int {
return len(s)
}
func less[T cmp.Ordered](lhs, rhs T) bool {
return lhs < rhs
}

View File

@@ -356,3 +356,20 @@ func TestIntersection(t *testing.T) {
}
}
}
func BenchmarkListSmall(b *testing.B) {
s := sets.New("a", "b", "c", "d", "e", "f", "g", "h", "i", "j")
for b.Loop() {
sets.List(s)
}
}
func BenchmarkListLarge(b *testing.B) {
s := make(sets.Set[int], 12345)
for i := range 12345 {
s.Insert(i * 7)
}
for b.Loop() {
sets.List(s)
}
}