g3n / engine

Go 3D Game Engine (http://g3n.rocks)
https://discord.gg/NfaeVr8zDg
BSD 2-Clause "Simplified" License
2.79k stars 295 forks source link

Unclear how to properly dispose of nodes #218

Closed ekuusi closed 2 years ago

ekuusi commented 3 years ago

Not really an issue, but rather a question.

I'm disposing of nodes with scene.remove and then nulling the slice that contained references to the nodes, like so:

func (a *animator) clearNodeGroup(nodes []*core.Node) []*core.Node {

    for _, node := range nodes {
        a.scene.Remove(node)
    }
    nodes = nil

    return nodes
}

a.clearNodeGroup(a.allLines)

However, I seem to be running into memory issues over time, so I'm not sure if I need to do something else to dispose of the nodes. Haven't been able to figure out anything else that would cause the slowdowns and memory problems. If the scene is on pause, not insterting / removing any nodes, it can run for ages.

gremour commented 3 years ago

Just stumbled upon this library. Here's my advice from the Go language point of view.

You're passing nodes as a variable copy to this function. Nulling it has no effect (it's a local variable). You need to remove the reference to variable you pass to this function (i.e. assign it to nil) to let GC collect it.

If I understand correctly your use case, here's an example:

type Animator struct {
    allLines []*core.Node
}

// ...

a.clearNodeGroup(a.allLines)
a.allLines = nil

Another approach is to pass a pointer to slice to the function (I've removed unused return result):

func (a *animator) clearNodeGroup(nodes *[]*core.Node) {
    for _, node := range *nodes {
        a.scene.Remove(node)
    }
    *nodes = nil
}

a.clearNodeGroup(&a.allLines)
danaugrs commented 2 years ago

This might have been fixed by https://github.com/g3n/engine/pull/214. Closing tentatively. Please reopen if you encounter this again!