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条)

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)