I know that the following will cause a memory leak (included fix):
--Part never gets garbage collected do local p = Instance.new('Part') local dataTable = {Message = "Test"; Part = p} p.Touched:connect(function() print(dataTable.message) end) end --FIX Part gets garbage collected do local p = Instance.new('Part') local dataTable = {Message = "Test"; Part = p} p.Touched:connect(function() print(dataTable.message) end) p.Destroy() end
This will also cause a memory leak (included fix)
--The coinTable will store every player that has ever initiated this remote event on this server local replicatedStorage = game:GetService("ReplicatedStorage") local remoteEvent = replicatedStorage.RemoteEvent local coinTable = {} --This is temporary and does not need to be saved in a datastore local function addCoins(player) local coins = coinTable[player.UserId] if coins then coins = coins + 1 coinTable[player.UserId] = coins else coinTable[player.UserId] = 1 --started at 1 to simulate adding a coin end for i,v in pairs(coinTable) do print(i, v) end end remoteEvent.OnServerEvent:Connect(addCoins) --FIX adding this will clean up the table entry players.PlayerRemoving:Connect(function(player) coinsTable[player.UserId] = nil end)
Is there anything else I'm missing that could cause a memory leak? I don't use temporary scripts and have little to no instances. If my events are permanent as well as my functions, am I good to go? Thank you
You most likely will never have to worry about garbage collection unless you are going to dabble with OOP using module scripts. As long as you know you don't need anything ever again, set it or its parent to nil and it'll be marked for collection.
Also, you don't need to iterate through a table to set everything inside to nil, just set the entire table to nil and it'll get rid of the whole thing.
And one last thing, if you have an outside variable referencing something in a table that has been garbage collected, it will just be set to nil, which is nice, but in large scripts, it can make debugging confusing, so make sure to handle this when you set entire tables to nil.