How does Garbage Collection on Tables work?

I was testing out garbage collection behaviors with this script:

game:GetService("RunService").Heartbeat:Connect(function()
	print(gcinfo())
end)

task.wait(1)

local srcTbl = {}

task.wait(1)

for i = 1, 1000000, 1 do
	srcTbl[i] = {
		AValue = "Hello World!"
	}
end

task.wait(3)

table.clear(srcTbl)
print("Cleared")

But for some reason, after clearing, some memory still didn’t get cleaned up.

Before the tables creation (expected):
image
After the tables creation (expected):
image
After srcTable was cleared (unexpected):
image

Could someone please explain why this is happening? Thank you in advance.

2 Likes

I’m also slightly confused. Does setting srcTbl to nil change any behavior?

1 Like

It’s worse, actually. The memory use stays the same before and after setting it to nil.

image

3 Likes

Im having some difficulty with my game too.

What I’m doing with every table is I created a function that cleans it deeply and removes every key.

So it’s like

Function DeepClean

function DeepCleanTable(t)
  for k, v in pairs(t) do
    if type(v) == "table" then
      DeepCleanTable(v)
    end
    t[k] = nil
  end
end
2 Likes

I believe table.clear functions the same way.

2 Likes

It won’t, because you are only clearing the 1st level keys.

If you have a table inside of a table inside of a table

then table.clear wont delete the other 2 tables

Oh, I see. Table.clear only works with an array and the method you listed works with dictionaries.

1 Like

Might be a 2 month old post but perhaps using the debug library will yield different results than gcinfo() as gcinfo is total memory heap and seems to be global across all scripts also you cannot really confirm if garbage collection will happen after the task.wait(3) or only after the script stops running and perhaps needs to be measured with another script instance, not much documentation on gcinfo as well for this type of usage.