mirror of
https://github.com/samber/lo.git
synced 2026-04-22 15:37:14 +08:00
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:
@@ -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] {
|
||||||
|
|||||||
@@ -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]++
|
||||||
|
|||||||
Reference in New Issue
Block a user