download201401 2016-04-20 14:59 采纳率: 0%
浏览 18
已采纳

我是否需要将地图设置为nil才能进行垃圾收集?

Let's say I have a simple map with string as keytype and a self-defined struct as valuetype. Like this: map[string]*struct

I populate this map with a lot of different values and a lot of these values will never be used again after a certain period of time.

So I wasn't sure whether the golang garbage collector will clean up my map for me or I need to do it myself. Then I came across this answer on a different question: Is it safe to remove selected keys from Golang map within a range loop?

This makes it look like the garbage collector won't do it for me and my only solution is to set my map to nil if i want to free up some memory every now and then.

Is this true? Or is there another way to do it without losing values in my map that are not 'inactive'?

  • 写回答

2条回答 默认 最新

  • dongshen7561 2016-04-20 19:41
    关注

    To try and answer this fully, we need to figure out what the question is exactly.

    For the title question:

    Do I need to set a map to nil in order for it to be garbage collected?

    No, once the map value is out of scope, it will be garbage collected like any other value.

    I populate this [map[string]*stuct] map with a lot of different values and a lot of these values will never be used again after a certain period of time.

    This example map you show contains pointer values, and for as long as they are contained in the map, the values to which they point will never be collected. Deleting the values from the map (using delete or setting the key to another value) will allow the memory referenced by the pointers to be collected. There is no special handling that needs to be done around a map to ensure garbage collection.

    Now, the internal structures of a map are not currently compacted, and small values (including pointers, and anything under 128 bytes) are stored directly in the hash buckets. A map with millions of entries isn't going to get smaller immediately after deleting those entries, so if you need to free that memory it's best to copy the remaining values you want to a new map. This is analogous to having a large slice that's no longer needed except for a few values, where you need to copy the remaining values to a new slice to free the original backing array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)