mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-17 11:12:28 +08:00
maputil: preallocate len and cap for keys and values slice (#41)
Length of keys and values is know in advance, use this knowledge to preallocate memory. Space usage increases by const factor
This commit is contained in:
@@ -8,10 +8,12 @@ import "reflect"
|
|||||||
|
|
||||||
// Keys returns a slice of the map's keys
|
// Keys returns a slice of the map's keys
|
||||||
func Keys[K comparable, V any](m map[K]V) []K {
|
func Keys[K comparable, V any](m map[K]V) []K {
|
||||||
keys := make([]K, 0, len(m))
|
keys := make([]K, len(m))
|
||||||
|
|
||||||
|
var i int
|
||||||
for k := range m {
|
for k := range m {
|
||||||
keys = append(keys, k)
|
keys[i] = k
|
||||||
|
i++
|
||||||
}
|
}
|
||||||
|
|
||||||
return keys
|
return keys
|
||||||
@@ -19,10 +21,12 @@ func Keys[K comparable, V any](m map[K]V) []K {
|
|||||||
|
|
||||||
// Values returns a slice of the map's values
|
// Values returns a slice of the map's values
|
||||||
func Values[K comparable, V any](m map[K]V) []V {
|
func Values[K comparable, V any](m map[K]V) []V {
|
||||||
values := make([]V, 0, len(m))
|
values := make([]V, len(m))
|
||||||
|
|
||||||
|
var i int
|
||||||
for _, v := range m {
|
for _, v := range m {
|
||||||
values = append(values, v)
|
values[i] = v
|
||||||
|
i++
|
||||||
}
|
}
|
||||||
|
|
||||||
return values
|
return values
|
||||||
|
|||||||
Reference in New Issue
Block a user