Does parenting an Instance to nil leak memory if there are no connections?

Suppose I never :Connect() any connections to any signals in the Instance then parent the Instance to nil instead of calling :Destroy()

For example

do
    local Part = Instance.new("Part")
    -- Set Part Properties
    local Part0 = Instance.new("Part")
    -- Set Part0 Properties
    Part.Parent = game
    Union = Part:SubtractAsync({Part0})
    Part.Parent = nil -- Is This OK?
end

Also no references to the Instance are retained

Is this code OK?

2 Likes

Hello Asadefa!

The moment that any instance is parented to game or a descendant of game, internal ROBLOX can connect connections to that instance (and probably will depending on its parent; it really depends on where it is). In your case, parenting a part to game might not connect any internal connections, but putting it in workspace would be different. I would highly recommend calling :Destroy() on the instance if you do not plan on using it again after that point.

4 Likes

It probably won’t but it’s still good practice to always destroy what you no longer need to prevent any edge cases or even obvious cases where something may be able to hook a connection or reference to that object later and keep it alive.

2 Likes

Should I :Destroy() objects that are parented to nil and were never parented to any other instance at any point?

Hello Asadefa!

Technically, they would be the same as Destroyed instances if they were never parented to anywhere (and therefore no connections should have been connected, unless manually done in Lua by you) but nil. I would still destroy them just to be on the safe side though.

Sets the Instance.Parent property to nil, locks the Instance.Parent property, disconnects all connections and calls Destroy on all children. This function is the correct way to dispose of objects that are no longer required.

That’s all destroy does. So if you don’t have connections or children, setting the parent to nil and dropping the reference looks equivalent to me.

However,

This function is the correct way to dispose of objects that are no longer required.

So I would say, why risk it, and just call Destroy.

I’m kinda scared of the word “parented to nil” because imagine if i was parented to nil? i would be nothing and i wouldn’t be able to come back!

2 Likes