Golang How do I delete a map?

Source: Internet
Author: User
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)}
    1. Map is emptied. Call the function after execution len , the result is definitely 0;
    2. Memory is not released. Empty just modifies a tag, the underlying memory is still occupied;
    3. 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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.