Better way to collect garbage

This my method to collect and clear a table, could this be improved or is it better off itself?

function __collectgc(t)
	xpcall(function(...) 
		for k,v in t do
			if typeof(v) == "RBXScriptConnection" then
				v:Disconnect()
			end
			k = nil
			v = nil
		end
	end, function(a0) 
		print(a0) 
	end)
end
1 Like

Hello!

If I may ask, why use protected calls? You have the necessary type check in place, making sure the object is in fact a script connection.

A second minor overlook are lines 7 and 8. Setting k and v returned by the iterator to nil will not have any impact over the table.

local part = Instance.new("Part")
local connectionList = {
	part:GetPropertyChangedSignal("Name"):Connect(function() end);
	"Just an innocent attempt to cause some trouble";
	part:GetPropertyChangedSignal("Color"):Connect(function() end);
}

function __clearconnections(t)
	for k,v in t do
		if typeof(v) == "RBXScriptConnection" and v.Connected then
			v:Disconnect()
		end
	end
	table.clear(t)
end

__clearconnections(connectionList)
print(connectionList) --> {}

Caveats

  1. table.clear() preserves allocated memory.
  2. The proper way to clean a table and cause a change in preserved space is using t[k] = nil.
  3. Disposing the old table by assigning a new one is an alternative, but I prefer the above two points.

Nevertheless! Setting a key or index to nil isn’t detected in order to improve assignment performance. That means assigning nil doesn’t shrink the table size until some non-nil elements are inserted to cause a rehash (which creates space allowing for more elements to be added).


EDIT. @weakroblox35

Yes, it does. Any mixed tables too.

3 Likes

It does clear dictionaries too right? Since my usual tables are constructed like this.
image

1 Like

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