douxi0098 2015-10-28 07:56
浏览 238

清除golang中的切片是否可以保证垃圾收集?

I wanted to implement time based slots for holding data using golang slices. I managed to come up with a go program like this and it also works. But I have few questions regarding garbage collection and the general performance of this program. Does this program guarantee garbage collection of items once slice is equated to nil? And while shuffling slices, I hope this program does not do any deep copying.

type DataSlots struct {
    slotDuration  int //in milliseconds
    slots         [][]interface{}
    totalDuration int //in milliseconds
}

func New(slotDur int, totalDur int) *DataSlots {
    dat := &DataSlots{slotDuration: slotDur,
        totalDuration: totalDur}
    n := totalDur / slotDur
    dat.slots = make([][]interface{}, n)
    for i := 0; i < n; i++ {
        dat.slots[i] = make([]interface{}, 0)
    }
    go dat.manageSlots()
    return dat
}

func (self *DataSlots) addData(data interface{}) {
    self.slots[0] = append(self.slots[0], data)
}

// This should be a go routine
func (self *DataSlots) manageSlots() {
    n := self.totalDuration / self.slotDuration
    for {
        time.Sleep(time.Duration(self.slotDuration) * time.Millisecond)
        for i := n - 1; i > 0; i-- {
            self.slots[i] = self.slots[i-1]
        }
        self.slots[0] = nil
    }
}

I removed critical section handling in this snippet to make it concise.

  • 写回答

2条回答 默认 最新

  • duanliang1898 2015-10-28 13:38
    关注

    Once your slice is set too nil, any values contained in the slice are available for garbage collection, provided that the underlying array isn't shared with another slice.

    Since there are no slice operations in your program, you never have multiple references to the same array, nor are you leaving data in any inaccessible portions of the underlying array.

    What you need to be careful of, is when you're using slice operations:

    a := []int{1, 2, 3, 4}
    b := a[1:3]
    a = nil
    // the values 1 and 4 can't be collected, because they are
    // still contained in b's underlying array
    
    c := []int{1, 2, 3, 4}
    c = append(c[1:2], 5)
    // c is now []int{2, 5}, but again the values 1 and 4 are
    // still in the underlying array. The 4 may be overwritten
    // by a later append, but the 1 is inaccessible and won't
    // be collected until the underlying array is copied.
    

    While append does copy values when the capacity of the slice in insufficient, only the values contained in the slice are copied. There is no deep copy of any of the values.

    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂