Free memory of slice

Could Go garbage collector free the slice underlying memory in this example?

    //Suppose I create a slice of int with size of 100:
    s := make([]int, 100)
    //Later, I only need the last 10 element of slice s and first 90 
    //element would never be accessed. so I trim it like this:
    s = s[90:]

My code would never access the elements of original slice s from 0 to 89. In this situation, could Go garbage collector free the memory allocated to them(s[0:89])? Or the memory would not be freed since it seems they still share the same underlying array on which slice s is built? If not, how should I do if I want to free those memory?(For example, I have to make a deep copy of slice and never access s)

1 Like

My code would never access the elements of original slice s from 0 to 89. In this situation, could Go garbage collector free the memory allocated to them(s[0:89])?

It could, but it currently does not.

Or the memory would not be freed since it seems they still share the same underlying array on which slice s is built?

Yes, the memory will not be free’d. This is similar to other languages that support “subslicing” vector types, like Java’s String type.

If not, how should I do if I want to free those memory?(For example, I have to make a deep copy of slice and never access s)

x := make([]int, 10)
copy(x, s)
s = nil // or let all references to s go out of scope
1 Like

Garbage collectors work at object level. That is, the Go GC would only collect the whole array once it is not used anymore, but it certainly does not look into objects in order to trim away unused parts of an array. (Or at least I would be very surprised if it does.)

The post "Go slices: usage and internals from the Go blog says,

The full array will be kept in memory until it is no longer referenced. Occasionally this can cause the program to hold all the data in memory when only a small piece of it is needed

(Near the end of the article, in section “A possible gotcha”.)

This Blog post is from 2011, and the GC has improved since then, but as said above, I’d be surprised if it trims arrays.

how should I do if I want to free those memory?

To ensure that the array is no longer referenced and thus can be collected by the GC, simply copy the slice over to another slice that is based on a different array.

This stackoverflow post contains some more interesting details.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.