Skip to content

Commit

Permalink
utils/map: preallocate memory
Browse files Browse the repository at this point in the history
Preallocate memory for result of MapKeys and MapValues to avoid expensive reallocations and further GC actions.

Signed-off-by: Florian Lehner <florian.lehner@elastic.co>
  • Loading branch information
florianl committed Oct 9, 2023
1 parent baaff43 commit 522673b
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions internal/build/utils/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,29 @@
package utils

// MapKeys returns the map keys as a slice of strings.
//
func MapKeys(s interface{}) (keys []string) {
func MapKeys(s interface{}) []string {
if s, ok := s.(map[interface{}]interface{}); ok {
keys := make([]string, 0, len(s))
for k := range s {
if k, ok := k.(string); ok {
keys = append(keys, k)
}
}
return keys
}
keys := make([]string, 0)
return keys
}

// MapValues returns the map values as a slice of interfaces.
//
func MapValues(s interface{}) (values []interface{}) {
func MapValues(s interface{}) []interface{} {
if s, ok := s.(map[interface{}]interface{}); ok {
values := make([]interface{}, 0, len(s))
for _, v := range s {
values = append(values, v)
}
return values
}
values := make([]interface{}, 0)
return values
}

0 comments on commit 522673b

Please sign in to comment.