Fast map -> array serialazier?

Hi Everyone, quick question here. :upside_down_face:

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

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 :slight_smile:

1 Like

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

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. :upside_down_face: