Karl
(Karl)
October 26, 2024, 1:36pm
1
Hi Everyone, quick question here.
If you have a large map like map[key]value what is the fastest way to serialize it to value only?
Pre-allocating the new slice and then running an append loop is my current way of doing it.
I do not care about the order of items. And hence I wonder if there is a faster way.
Thanks a lot.
In view of the practicality, this approach is not controversial.
var m map[key]value
l := make([]value, 0, len(m))
for _, v := range m {
l = append(l, v)
}
If the efficiency still doesn’t meet your expectations, you might want to consider changing your data structure.
1 Like
GonzaSaya
(Gonzalo Sayago)
October 28, 2024, 7:17pm
3
Did you tried something like
var m map[key]value
i:=0
l := make([]value, len(m))
for _, v := range m {
l[i] = v
i++
}
or
var m map[key]value
i:=0
l := make([]value, len(m))
for k := range m {
l[i] = m[k]
i++
}
?
Share your results with data types
1 Like
falco467
(Falco Wockenfuß)
October 31, 2024, 2:09pm
4
If the performance really matters that much, you should take a step back and look at the code which is creating the map. The fastest Option will probably be to create the array immediately with the same code that is now creating the map.
I had the same thought. That or just use the map. Why do you need to convert it to an array/slice in the first place if order doesn’t matter?
1 Like
Karl
(Karl)
October 31, 2024, 8:56pm
6
Thank you for your commitment, but I don’t have a speed problem. Or rather, I have solved it very quickly. It was more a matter of principle.