perf: add map capacity hints to Mode and it.UniqKeys/UniqValues (#837)

- Mode: make(map[T]int) → make(map[T]int, len(collection))
- it.UniqKeys: compute total size from input maps for seen map hint
- it.UniqValues: compute total size from input maps for seen map hint

Avoids repeated map rehashing as entries are added.
This commit is contained in:
Samuel Berthe
2026-03-06 17:10:17 +01:00
committed by GitHub
parent 6572c7fd22
commit e9ad51b03a
2 changed files with 11 additions and 3 deletions
+10 -2
View File
@@ -27,7 +27,11 @@ func Keys[K comparable, V any](in ...map[K]V) iter.Seq[K] {
// Play: https://go.dev/play/p/_NicwfgAHbO // Play: https://go.dev/play/p/_NicwfgAHbO
func UniqKeys[K comparable, V any](in ...map[K]V) iter.Seq[K] { func UniqKeys[K comparable, V any](in ...map[K]V) iter.Seq[K] {
return func(yield func(K) bool) { return func(yield func(K) bool) {
seen := make(map[K]struct{}) var total int
for i := range in {
total += len(in[i])
}
seen := make(map[K]struct{}, total)
for i := range in { for i := range in {
for k := range in[i] { for k := range in[i] {
@@ -62,7 +66,11 @@ func Values[K comparable, V any](in ...map[K]V) iter.Seq[V] {
// Play: https://go.dev/play/p/QQv4zGrk-fF // Play: https://go.dev/play/p/QQv4zGrk-fF
func UniqValues[K, V comparable](in ...map[K]V) iter.Seq[V] { func UniqValues[K, V comparable](in ...map[K]V) iter.Seq[V] {
return func(yield func(V) bool) { return func(yield func(V) bool) {
seen := make(map[V]struct{}) var total int
for i := range in {
total += len(in[i])
}
seen := make(map[V]struct{}, total)
for i := range in { for i := range in {
for _, v := range in[i] { for _, v := range in[i] {
+1 -1
View File
@@ -196,7 +196,7 @@ func Mode[T constraints.Integer | constraints.Float](collection []T) []T {
mode := make([]T, 0) mode := make([]T, 0)
maxFreq := 0 maxFreq := 0
frequency := make(map[T]int) frequency := make(map[T]int, len(collection))
for _, item := range collection { for _, item := range collection {
frequency[item]++ frequency[item]++