Will this cause a memory leak?

I made a variable and then set it to the clone of an object, after I destroyed the clone though (Used sound:Destroy()), will the variable cause the memory leak if I don’t set it to nil?

2 Likes

Yes, instance variables can cause memory leak if you’re not destroying the instance and set the variable to nil once you don’t need it anymore.
Here is an exemple:

local Sound = Instance.new("Sound")
--Do something with it
Sound:Destroy()
Sound = nil
3 Likes

Doesn’t it just become nil when thread ends? Do we really need to set it to nil?

You do not need to make the variable nil. After an object is destroyed it has no more references.
Edit: it actually doesn’t delete the reference but makes it unable for you to use it. Garbage collection handles everything else I believe

if you transfer it to another thread, example is as an index in a table, it will not have a parent or anything, but it does keep existing even after you destroy it. And you can run another :Destroy() in the other (indexed) thread if it does not have a parent etc. aswell. I don’t really know how it works or should we set it to nil.

My first answer was no, you don’t need to, but after doing some research i edited my message.

When an instance get destroyed, only its parent become nil, not the instance itself, so your variable still is indexing the instance.

If i understood it correctly, you have to destroy and set the variable to nil to guarantee to get it marked to go to the garbage collection, because if there still is references of this instance somewhere, it could be marked it still exist and still is actively used so it could not go to the garbage collection.

2 Likes

What is garbage collection? And what are threads?

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.