I wanted to implement temporary slots for storing data using golang slices. I managed to come up with such a program, and it also works. But I have few questions regarding garbage collection and the overall performance of this program. Does this program provide garbage collection when a slice equates to zero? And by shuffling the pieces, I hope this program does not do any deep copying.
type DataSlots struct {
slotDuration int
slots [][]interface{}
totalDuration int
}
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)
}
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 the processing of the critical section in this snippet to make it concise.
source
share