2

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:]
icza
  • 389,944
  • 63
  • 907
  • 827
FPGA
  • 3,525
  • 10
  • 44
  • 73
  • 1
    Sadly, yes. Maybe that's going to be improved in a future version of the Go language. – fuz Mar 03 '15 at 13:11

1 Answers1

4

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 = ""
Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827
  • what if it was a slice of strings?, do i just need to set it to empty string? – FPGA Mar 03 '15 at 12:44
  • 1
    @FPGA Then the values of the `string` elements will remain in memory and consume memory. – icza Mar 03 '15 at 12:45
  • so in that case i should make it a slice of pointers to strings? – FPGA Mar 03 '15 at 12:46
  • 1
    @FPGA No, you shoudln't. What I meant was that if you don't zero the elements then they will continue to occupy memory. You can zero `string` elements like this: `lines[0] = ""` (empty string is the zero element of a `string`). – icza Mar 03 '15 at 12:49
  • and it does get garbage collected after setting it to empty string? – FPGA Mar 03 '15 at 12:54
  • 1
    @FPGA Yes, if there are no other refernences to it. – icza Mar 03 '15 at 12:58