diff --git a/staging/src/k8s.io/apimachinery/pkg/util/sets/set.go b/staging/src/k8s.io/apimachinery/pkg/util/sets/set.go index cd961c8c593..ae3d15eb25f 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/sets/set.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/sets/set.go @@ -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 -} diff --git a/staging/src/k8s.io/apimachinery/pkg/util/sets/set_generic_test.go b/staging/src/k8s.io/apimachinery/pkg/util/sets/set_generic_test.go index 53f3383def7..e439a553d04 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/sets/set_generic_test.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/sets/set_generic_test.go @@ -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) + } +}