了解内存分配的工作方式和垃圾收集器

Say I am making an in-memory cache of several gigs. In order to free up space when the cache is reaching its maximum size, I will remove items that have not been accessed as often.

When I remove these items, will the memory be freed up for the computer to allocate to other processes and/or my application? I know Go uses a garbage collector so presumably, the operating system will not have access to that memory until it is garbage collected and then my application will consume fewer memory resources.

Is this correct?

How, exactly, will you remove items?

Comment:

so if I am storing the items in a slice I would do a = append(a[:i], a[i+1:]...) – Blankman

Which may or may not work. What type is the slice?


Go SliceTricks

Cut

a = append(a[:i], a[j:]...)

Delete

a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]

Delete without preserving order

a[i] = a[len(a)-1] 
a = a[:len(a)-1]

NOTE If the type of the element is a pointer or a struct with pointer fields, which need to be garbage collected, the above implementations of Cut and Delete have a potential memory leak problem: some elements with values are still referenced by slice a and thus can not be collected. The following code can fix this problem:

Cut

copy(a[i:], a[j:])
for k, n := len(a)-j+i, len(a); k < n; k++ {
  a[k] = nil // or the zero value of T
}
a = a[:len(a)-j+i]

Delete

copy(a[i:], a[i+1:])
a[len(a)-1] = nil // or the zero value of T
a = a[:len(a)-1]

Delete without preserving order

a[i] = a[len(a)-1]
a[len(a)-1] = nil
a = a[:len(a)-1]

In simple terms, the Go GC (garbage collector) retains memory until it is no longer used. Amongst other things, the GC follows all pointers in used memory, a deep usage analysis.


Go Frequently Asked Questions (FAQ): Why do garbage collection? Won't it be too expensive?

The Go Blog: Go GC: Prioritizing low latency and simplicity

The Go Blog: Getting to Go: The Journey of Go's Garbage Collector

Go 1.4+ GC Plan and Roadmap

The Garbage Collection Handbook: The Art of Automatic Memory Management (Chapman & Hall/CRC Applied Algorithms and Data Structures series) R. Jones, A. Hosking, E. Moss