1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52: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:
donutloop
2022-07-19 09:04:19 +02:00
committed by GitHub
parent 44370aef5e
commit ecf325a06c

View File

@@ -8,10 +8,12 @@ import "reflect"
// Keys returns a slice of the map's keys
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 {
keys = append(keys, k)
keys[i] = k
i++
}
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
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 {
values = append(values, v)
values[i] = v
i++
}
return values