Do golang slices clean garbage collection guarantees?

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 //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 the processing of the critical section in this snippet to make it concise.

+4
source share
2 answers

nil, , , , , .

, , .

, , :

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 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 in inaccessible and won't
// be collected until the underlying array is copied.

append , , , . - .

+3

, ?

- , .

:

import "runtime/debug"

...

debug.FreeOSMemory()

https://golang.org/pkg/runtime/debug/#FreeOSMemory

func FreeOSMemory()

FreeOSMemory , . ( , .)

0

Source: https://habr.com/ru/post/1613446/


All Articles