垃圾回收
runtime包中的垃圾回收机制可以自动地回收不再使用的内存,如下所示:
代码语言:javascript复制package main
import (
"fmt"
"runtime"
"time"
)
func main() {
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
fmt.Printf("Alloc = %v MiBn", mem.Alloc/1024/1024)
fmt.Printf("TotalAlloc = %v MiBn", mem.TotalAlloc/1024/1024)
fmt.Printf("HeapAlloc = %v MiBn", mem.HeapAlloc/1024/1024)
fmt.Printf("HeapSys = %v MiBn", mem.HeapSys/1024/1024)
for i := 0; i < 10000; i {
data := make([]byte, 1024*1024)
time.Sleep(time.Millisecond)
}
runtime.GC()
runtime.ReadMemStats(&mem)
fmt.Printf("Alloc = %v MiBn", mem.Alloc/1024/1024)
fmt.Printf("TotalAlloc = %v MiBn", mem.TotalAlloc/1024/1024)
fmt.Printf("HeapAlloc = %v MiBn", mem.HeapAlloc/1024/1024)
fmt.Printf("HeapSys = %v MiBn", mem.HeapSys/1024/1024)
}
上面的代码先打印出内存分配前的内存信息,然后分配10000个1MB的内存块,并睡眠1毫秒,以便让垃圾回收机制起作用。最后打印出内存回收后的内存信息。