垃圾回收是释放未使用的内存空间的过程。换句话说,垃圾收集器查看哪些对象不在范围内并且无法再引用,并释放它们消耗的内存空间。此过程在 Go 程序运行时(而不是在程序执行之前或之后)以并行方式发生。 Go 垃圾收集器实现的文档指出以下内容:
The GC runs concurrently with mutator threads, is type accurate (aka precise), allows multiple GC thread to run in parallel. It is a concurrent mark and sweep that uses a write barrier. It is non-generational and non-compacting. Allocation is done using size segregated per P allocation areas to minimize fragmentation while eliminating locks in the common case.
垃圾回收是和 goroutine 同时运行的,它是类型精确的,而且多个垃圾回收线程可以并行运行。它是一种使用了写屏障的并发标记清除的垃圾回收方式。它是非分代和非压缩的。使用按 P 分配区域隔离的大小来完成分配,以最小化碎片,同时消除常见情况下的锁。
func main() {
var mem runtime.MemStats
printStats(mem)
for i := 0; i < 10; i++ {
s := make([]byte, 50000000)
if s == nil {
fmt.Println("Operation failed!")
printStats(mem)
for i := 0; i < 10; i++ {
s := make([]byte, 100000000)
if s == nil {
fmt.Println("Operation failed!")
time.Sleep(5 * time.Second)
}
}
printStats(mem)
}