我在想,当我创建System struct
时,构建器系统将耗费大量内存,但结果很简单,所以如果我返回结果的地址,那么垃圾会知道吗它可以收集构建器系统内存吗?
如何测试?
我模拟这样的情况:
// Builder is used to build `System`, and it will cost much memory
type Builder struct {
aux [][]int
system *System
}
// System is the result of `Builder.build`, this is relatively simple
type System struct {
avg []float32
}
func NewSystem() *System {
builder := &Builder{system: &System{}}
builder.build()
return builder.system
}
func (builder *Builder) build() {
// mock initialize
maxCnt := 10000
builder.aux = make([][]int, maxCnt)
for i := range builder.aux {
builder.aux[i] = make([]int, maxCnt)
for j := range builder.aux[i] {
builder.aux[i][j] = rand.Intn(maxCnt)
}
}
builder.system.avg = make([]float32, len(builder.aux))
for i, col := range builder.aux {
var sum float32
for _, row := range col {
sum += float32(row)
}
builder.system.avg[i] = sum / float32(len(builder.aux))
}
}
func TestMem(t *testing.T) {
system := NewSystem()
// I want to know can garbage know that the memory cost by builder is able to be collected
fmt.Println("do many things with system")
fmt.Println(system.avg)
}
答案 0 :(得分:1)
是的,一旦有足够的内存压力来触发垃圾收集,它就会被垃圾收集(假设它甚至放在堆上;分配给堆栈的任何东西都不需要进行垃圾收集,因为整个堆栈在解除分配时会被释放不再使用)。垃圾收集器将释放任何没有剩余引用的东西。处理完成后,唯一带参考的是[]float32
。如果那是一块结构,并且那些结构有一个指向父对象的指针,那将阻止父进程被收集。