Trying to fix memory leaks in my game but as far as I can see I am cleaning up my connections just fine.
The only thing I am doing a lot of is deleting scripts when a player dies (UI and local character scripts).
I assumed that any tables or connections inside of the localscript would automatically be cleaned up.
But in a fresh place I have just this script, and I noticed it never does get cleaned up.
local script in playergui
task.wait(5)
local ta = {}
for i = 1, 10000000 do
table.insert(ta, "8gfn0248g2n4og")
end
print'done'
task.wait(10)
print(ta)
This raised the Client Memory Usage by about 300 (included video), then even when the script finishes, the memory doesn’t go down. Then I deleted the script (didn’t show in video, just cleared playergui in devconsole where the script is), and still nothing. I waited a few minutes just incase it took longer and it stayed high.
This was tested in-game.
Have I been misunderstanding memory this entire time? Do I need to ensure I cleanup tables/connections before I delete a script?
I stayed AFK in the game for about 15 minutes and it dropped about 300, the LuaHeap now says about 100, down from 400… that still seems insane for a blank place with basically no scripts.
Technically? I’m not 100% familiar with how the garbage collector works but i do know it functions based around some sort of memory pressure system. For example the garbage collector would be much quicker in trying to dump memory if the client memory was increasing memory by quite a bit or if the device simply does not have a lot of memory to work with. Though take my explanation with a grain of salt, as ive said, im not 100% familiar.
What i do know is that on higher end devices with plenty of memory, it’ll simply just take ages for the thing to do anything about any useless memory.
This is accurate. Pretty much all automatic garbage collectors work like you describe, and if you’re just sitting alone in your game after running a script like this, there are probably not enough other allocations happening for the garbage collector to need to run. There’s overhead (significant) in analyzing memory to figure out what memory can actually be freed, and even more to compact (defrag) memory, so it’s not done frequently, the GC waits for there to be a pressing need. You probably wouldn’t want a trash truck coming to your house every 5 minutes to check if you’ve thrown out a tissue or an Amazon box, right? Same idea.
A better test would be to run your script every few seconds, for a long session. The memory usage should ideally have a sawtooth shape, ramping up, falling off sharply when collection happens, repeating. If there is a true memory leak, the usage will creep up over the long term, across many collection cycles.