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 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集