Destroy() and nil or just nil

No there was standing the Instance will not be destroyed completly until i would set it to nil

Actually @AGIT_Games is correct. An object won’t be fully deleted until there are no references to it, or in other words until all of the variables are reassigned or nil. This is because the Destroy only prepares the object for deletion, it doesn’t actually remove it from memory. The garbage collector removes it from memory, but only if there are no more references to it. You can go delete a part, change the CFrame, print the changed CFrame, wait 30 minutes and it will still exist which you can see by using one of its properties like BrickColor or one of its methods like FindFirstChild.

It almost never matters because local variables become nil when they go out of scope, so it’s not something most people need to worry about. But you may need to worry if you have a table with ten thousand pointers to removed instances as either a global variable or a local variable that never goes out of scope. The solution there would be to just remove the destroyed parts from the table as you destroy them, or let the variable pointing to the table become reassigned or nil.

Don’t take my word for it. Here’s some code I just ran to prove it. Paste it into the console and run it if you have a few minutes and at least 8 gigs of ram installed in your computer.

local parts = {}
warn("Generating parts.")
for i = 1, 1000000 do
	local part = Instance.new("Part")
	parts[i] = part
end
warn("Arrived at checkpoint 1. All parts created.\
Record memory usage in task manager,\
then run _G.go=true in the console to proceed.")
_G.go = nil
repeat task.wait() until _G.go
for i = 1, 1000000 do
	parts[i]:Destroy()
end
warn("Arrived at checkpoint 2. All parts destroyed.\
Wait fifteen minutes or so, then record memory usage.\
Then run _G.go=true in the console to proceed.\
Note: Studio's own memory usage may naturally fluctuate\
up or down by several hundred megabytes over time.")
_G.go = nil
repeat task.wait() until _G.go
_G.go = nil
parts = nil
warn("Script finished. References to parts removed.\
Wait for the garbage collector to remove all parts in memory,\
then note the decrease in memory usage.\
You will likely see the memory usage start to drop\
within the next ten seconds.")
9 Likes

Thanks for the explanation! I will try the Code later.

Ah I see my bad then. I better keep an eye out for that in my code to reduce any memory loss due to having references to something, most of the variables I use are local anyways at the moment.

2 Likes