Senior
If you create a map, add a million values, then delete all elements and call GC — will the memory return to its original state?
sobes.tech AI
Answer from AI
In Go, if you create a map with a million elements, then delete all elements and invoke the garbage collector (GC), the memory does not necessarily return to its original level immediately.
Reasons:
- The map internally uses a hash table with an allocated buffer. When elements are deleted, the structure remains the same size, but the elements become nil.
- The GC will free the memory occupied by the values, but the map's structure (hash table) remains allocated.
- To reduce memory usage, you can create a new map and copy the necessary elements into it, or assign nil to the old map so that the GC can free all the memory.