Saturday, December 2, 2023
HomeGolangWhy does golang fail to reclaim the reminiscence after assigning a worldwide...

Why does golang fail to reclaim the reminiscence after assigning a worldwide variable to nil? – Getting Assist


Code as beneath, foo.bar cannot be reclaimed by runtime.GC() after foo = nil.

package deal important

import (
	"os"
	"runtime"
	"runtime/pprof"
)

sort FooStruct struct {
	bar map[int]int
}

var foo = &FooStruct{
	bar: map[int]int{},
}

func forceGC() {
	file, _ := os.Create("mem.prof")
	runtime.GC()
	pprof.WriteHeapProfile(file)
}

func setBarMap() {
	for i := 0; i < 1000000; i++ {
		foo.bar[i] = i
	}
}

func important() {
	setBarMap()

	foo = nil

	forceGC()
}

Why does runtime.GC() fail to reclaim the reminiscence after foo = nil


Evidently runtime.mapassign_fast64 references the tackle pointed by important.foo(SB) .

Does the underlying construction of foo.bar reference the tackle pointed to by important.foo(SB) ?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments