Which methods of functions create memory leaks?

I know there are different types of functions, but I was wondering if any of these types cause memory leaks in the context of a script that is inside a Tool, Gui, or anything else that will get destroyed once the character dies and respawns again. I am also wondering if any of these are overly complicated with 0 advantage over another method of functions.

1: Connecting an event and disconnecting once the script is no longer needed (like when the character dies, for example)

local event
local disconnectevent
function DisconnectEvents()
   if event then
      event:Disconnect()
   end
   if disconnectevent then
      disconnectevent:Disconnect()
   end
end
function Function1()
   --Stuff here
end

2: Connecting an event but not disconnecting it

function Function1()
   --Stuff here
end
script.Parent.Activated:Connect(Function1)

3: Not saving the function as a variable and also not disconnecting it

script.Parent.Activated:Connect(function()
   --Stuff here
end)
1 Like

From my understanding, Events are disconnected if the script that they are in is destroyed. Since when the Character respawns, the Character is destroyed these scripts would be destroyed and would therefore not create a memory leak.

However, memory leaks can appear if the instance or script isn’t destroyed. If I understand your post correctly this wouldn’t be the case since they would be destroyed.

1 Like