The Go developer doesn’t have to manually release memory for variables and structures that are no longer used in the program. A separate process in the Go runtime, the garbage collector, takes care of that. It periodically searches for variables that are no longer referenced and frees their memory. Functionality related to this process can be accessed via the runtime package.
Garbage collection can be explicitly invoked by calling the runtime.GC()
function, but this is only useful in rare cases, such as when memory resources are scarce. In such cases, a large chunk of memory could be immediately freed at that point in the execution, and the program can afford a momentary decrease in performance due to the garbage collection process.
If you want to know the current memory status, use:
package main
import (
"runtime"
"time"
)
func main() {
ms := runtime.MemStats{}
runtime.ReadMemStats(&ms)
println("Heap after GC. Used:", ms.HeapInuse, "Free:", ms.HeapIdle, "Meta:", ms.GCSys)
time.Sleep(5 * time.Second)
}