重新切片和垃圾收集

Re-slicing and garbage collection

重新分片时,是否需要将不在分片中的元素设置为nil,对垃圾回收有影响吗?

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:]
}

更新:

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

简答:是。

重新切片或数组后,新切片中不可见的元素不会自动归零。由于后备数组保存在内存中,所以元素也保存在内存中。

有关详细信息,请参阅 。引用相关部分:

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.

更新:

您更新后的代码可以这样归零:

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

注意:复制元素并将它们置零不会将数组中的值置零,因此这没有效果:

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 = ""