Will my instantiated object (OOP) get garbage collected after :Destroy() method called?

Hi. Making a Capture The Flag game and I’m using OOP for a Flag object. I want to instantiate a new Flag object every round and destroy it at the end of the round.

Currently, I have a :Destroy() method in my Flag class which uses a Maid object to destroy the flag’s model and also disconnects any connections in my flag object:

function Flag:Destroy()
    self._maid:GiveTask(self.model)
    self._maid:Destroy() -- Cleans up all connections + destroys self.model 
end

If I have a setup on a server script like this:

local Flag = Flag.new(...)
Flag:Destroy()
Flag = nil

Will my flag object get garbage collected? I’m just concerned a bit about memory (which I’m 100% not very knowledegable about) since if it hangs around in memory then (as I’m instantiating a new Flag object every round) I assume my used Flag objects will take up a considerable amount of my server’s memory over time.
I’m also unsure on how to actually check whether it has been garbage collected or not as I don’t quite understand how to use Studio’s tools for checking memory usage.

My other solution is to make it so I can reuse the same Flag object every round which may probably be better but I’d rather preserve my current method out of convenience.

AFAIK there isn’t really a good way of doing this, because in Roblox the __gc metamethod is disabled - apparently for security reasons.

You can check if your class implementation allows objects to be GCed by testing it in a separate place and just creating like 10000 flags, holding them for a few seconds and then removing references to them. Memory usage should go up when you create them, and back down again when they get GCed.

It’s still possible for users of your class to make mistakes that prevent flag objects from being GCed though, by keeping unneeded references to objects even after they’re “Destroy()ed”.

1 Like

Thanks for the very helpful reply. Any good forum posts that guide you on how to use studios tools for monitoring memory?

Not that I know of, sorry. Bumping for visibility, but you might have to make another post asking for that specifically becase AFAICT posts with answers/especially solutions don’t get a lot of views