Reputation: 3855
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:]
Upvotes: 2
Views: 903
Reputation: 417572
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 = ""
Upvotes: 4