Dictionary and Memory leaks

Hey guys,

Just wanted to clarify something about dictionaries.

For example, I have a localscript setup in StarterPlayerScripts

local tbl = {}
Remote.OnClientEvent:Connect(function(data)
	if preLoadAnim[player.Character] == nil then
		preLoadAnim[player.Character] = {}
	end
	if preLoadAnim[player.Character][data.Anim] == nil then
		preLoadAnim[player.Character][data.Anim] = player.Character.Humanoid.Animator:LoadAnimation(data.Anim)
	end 
end)

Now, we know that player.Character is defined again after a character dies - it becomes null

Thus I am left with 2 values in the dictionary tbl

I just want to know if this will cause memory leaks (untracked memory), if yes, how would I go fixing this issue?

Any feedback would be greatly appreciated

That would create a memory leak, since it would keep an active reference to the player’s character, thus preventing it from being garbage collected. It would need to be removed from the dictionary after the player’s character’s removed to prevent this.
For example,

player.CharacterRemoving:Connect(function(OldCharacter)
    for CharAnimData in next, preLoadAnim[OldCharacter] do
        preLoadAnim[OldCharacter][CharAnimData] = nil
    end
    preLoadAnim[OldCharacter] = nil
end)

Lemme know if you have any questions :+1:

2 Likes

So it doesnt matter if a the object in a key becomes nil, correct?

e.g. tbl[char.Humanoid] = “hi”
if char.Humanoid becomes nil, it doesnt matter?

and what happens if the script gets deleted that hold this table?

By doing Dict.Key = nil you’re removing the key and assigned value from the table. It doesn’t make the Humanoid be nil.

local Dict = {}
local Humanoid = Instance.new("Humanoid")
Dict[Humanoid] = Humanoid.MaxHealth

print(Dict[Humanoid]) -- 100
print(Humanoid) -- Humanoid
for Object in next, Dict do
    print(Object) -- Humanoid
end

Dict[Humanoid] = nil

print(Dict[Humanoid]) -- nil
print(Humanoid) -- Humanoid
for Object in next, Dict do
    print(Object) -- *nothing outputs*
end

–

Then the character would be up for garbage collection since there would no longer be an active reference to it.

1 Like