douqu2481 2015-03-03 12:38
浏览 22
已采纳

重新切片和垃圾收集

When re-slicing, do i need to set the elements that are not in the slice anymore to nil,does it have any effect on garbage collection?

type X struct {
  Value   string
}

func main() {
    Xs:=[]*X{&X{"a"},&X{"b"},&X{"c"},&X{"d"}}
    X0:= Xs[0]
    Xs[0] = nil //does this line has any effect on the garbage collector,is it necessary?
    Xs= Xs[1:]
}

Update:

strings:=[]string{"a","b","c","d"}
string0:= strings[0]
//how do i zero strings[0]?
strings = strings[1:]
  • 写回答

1条回答 默认 最新

  • doumibi6899 2015-03-03 12:41
    关注

    Short answer: yes.

    After reslicing a slice or array, elements that are not visible in the new slice are not zeroed automatically. And since the backing array is kept in memory, so are the elements stored in them.

    See this answer for more details. Quoting the relevant part:

    Also another very important thing is that if an element is popped from the front, the slice will be resliced and not contain a reference to the popped element, but since the underlying array still contains that value, the value will also remain in memory (not just the array). It is recommended that whenever an element is popped or removed from your queue (slice/array), always zero it (its respective element in the slice) so the value will not remain in memory needlessly. This becomes even more critical if your slice contains pointers to big data structures.

    Update:

    Your updated code could be zeroed this way:

    strings:=[]string{"a","b","c","d"}
    // IMPORTANT: zero before reslicing:
    strings[0] = "" // Empty string is the zero value of string
    strings = strings[1:]
    

    Note: Making a copy of the element(s) and zeroing them does not zero the values in array, so this has no effect:

    strings:=[]string{"a","b","c","d"}
    string0:= strings[0]
    strings = strings[1:]
    
    // This has no effect on the array, it just zeroes the variable string0
    string0 = ""
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭