SetFinalizer sets the finalizer associated with obj to the provided finalizer function. When the garbage collector finds an unreachable block with an associated finalizer, it clears the association and runs finalizer(obj) in a separate goroutine. This makes obj reachable again, but now without an associated finalizer. Assuming that SetFinalizer is not called again, the next time the garbage collector sees that obj is unreachable, it will free obj.
funcBar() { f1 := MakeFoo("one") f2 := MakeFoo("two")
fmt.Println("f1 is: ", f1.name) fmt.Println("f2 is: ", f2.name) }
funcmain() { for i := 0; i < 3; i++ { Bar() time.Sleep(time.Second) runtime.GC() } fmt.Println("done.") }
执行结果
1 2 3 4 5 6 7 8 9 10 11 12 13
f1 is: one f2 is: two a finalizer has run for two 1 a finalizer has run for one 0 f1 is: one f2 is: two a finalizer has run for two 3 a finalizer has run for one 2 f1 is: one f2 is: two a finalizer has run for two 5 a finalizer has run for one 4 done.
fmt.Printf("Allocation: %f Mb, Number of allocation: %d\n", float32(ms.HeapAlloc)/float32(1024*1024), ms.HeapObjects)
for i := 0; i < 1000000; i++ { f := NewFoo(i) _ = fmt.Sprintf("%d", f.a) }
runtime.ReadMemStats(&ms) fmt.Printf("Allocation: %f Mb, Number of allocation: %d\n", float32(ms.HeapAlloc)/float32(1024*1024), ms.HeapObjects)
runtime.GC() time.Sleep(time.Second)
runtime.ReadMemStats(&ms) fmt.Printf("Allocation: %f Mb, Number of allocation: %d\n", float32(ms.HeapAlloc)/float32(1024*1024), ms.HeapObjects)
runtime.GC() time.Sleep(time.Second)
runtime.ReadMemStats(&ms) fmt.Printf("Allocation: %f Mb, Number of allocation: %d\n", float32(ms.HeapAlloc)/float32(1024*1024), ms.HeapObjects) }
//go:noinline funcNewFoo(i int) *Foo { f := &Foo{a: rand.Intn(50)} runtime.SetFinalizer(f, func(f *Foo) { _ = fmt.Sprintf("foo " + strconv.Itoa(i) + " has been garbage collected") })
return f }
运行结果
1 2 3 4
Allocation: 0.121063 Mb, Number of allocation: 140 Allocation: 29.111671 Mb, Number of allocation: 1899990 Allocation: 128.025635 Mb, Number of allocation: 4382420 Allocation: 0.122147 Mb, Number of allocation: 155