Will golang free the memory when I use delete map[somekey]?

I have noticed the source code of golang’s implements of map:
when I use delete map[somekey] in my code, I find that golang will not delete the key, but mark the key as empty instead.

Here are my questions:
1 when a key was marked as empty, golang’gc will free the memory? and if not, when I initialize a map, and I delete keys and add different keys as time going by. This map may cause memory leak, Is that reasonable?
2 Why golang do like this(not actually delete the key and free memory but just mark the key empty)?

I am really confused about it!

Thank a lot.


Open Issue

Repeatedly adding and removing keys should not be a leak, it’s just that the map size is bounded to the maximum size it had at any point. This can be a problem sometimes, but usually it is not.

Note also that if this does matter, for example if you have a map[something]reallyLargeStruct then you can use a map[something]*reallyLargeStruct instead. The map just contains the pointer values and will not be very large by itself. The pointed-to values will get garbage collected.

2 Likes

Thats an extremely attractive solution :slight_smile:

There are other similar cases. For example if you implement a stack by having a slice that you append to when pushing and reslice down when popping. It will never shrink below below it’s maximum size (and you need to remember to zero out pointer values or those will also stick around). To shrink it you need a copy, which you can also do with a map.

1 Like

Thank you for your reply and it help me learn a lot .

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.