This is a creation in Article, where the information may have evolved or changed.
Delete operation of Map
Golang has built-in hash tables, which are generally implemented using hash lists, and if there is a hash conflict, put the conflicting content in a linked list.
Golang also has a built-in delete
function that, if acting on a hash table, deletes the key inside the map.
delete(intMap, 1)
How map is deleted
Can directly see the source code.
I'll simply pick a few lines:
func mapdelete(t *maptype, h *hmap, key unsafe.Pointer) { for ; b != nil; b = b.overflow(t) { for i := uintptr(0); i < bucketCnt; i++ { b.tophash[i] = empty h.count-- } }}
The outer loop is traversing the entire map, and the core of the deletion is at that empty
. It modifies the tag of the current key, rather than simply deleting the data inside the memory.
empty = 0 // cell is empty
How to clear the entire map
Looking at my analysis above, can this code empty the map?
for k, _ := range m { delete(m, k)}
- Map is emptied. Call the function after execution
len
, the result is definitely 0;
- Memory is not released. Empty just modifies a tag, the underlying memory is still occupied;
- The loop iterates through the
len(m)
times. The above code deletes an element each time it is traversed, and the number of iterations is not reduced by deleting one element at a time.
How do I really free up memory?
map = nil
After that, it's good to wait for the garbage collector to recycle.
If you use map for caching, and each update is only a partial update, the updated key if the deviation is relatively large, there may be a gradual increase in memory without releasing the problem . Be careful.