Refreshing inventory cause a memory leak

Hi Im making an inventory system and for each item in the inventory there is this Item.MouseButton1Down:Connect(function()

Everytime the player opens the inventory it destroys all existing buttons and create new ones, Im wondering if the MouseButton1Down connection will cause any lags or a memory leak since the button does not exist anymore

it shouldnt be an issue, but i have a janitor module that i can provide to you if you really wanna be sure, its open source and made by me (its pretty simple), just make a new one, on function call, call janitor clean, then wrap your connections in the janitor. heres a use example! The supported types are connections (clicks), instances, functions, and table for enums!

	MealJanitor:Clean()

	MealJanitor:Add(MealFrame.ResetButton.MouseButton1Click:Connect(function()
		DefinedPackets.MealTime:Fire(FoodPeriod, "Reset", "", "")
	end))
--[[

	Janitor by yoda962
	Used for cleanups
	4/1/2025
	
	MIT LISCENCE

]]

Janitor = {}
Janitor.__index = Janitor

function Janitor.new() --// makes a new janitor class
	local self = setmetatable({}, Janitor)
	self.Cleanup = {}
	return self
end

function Janitor:Add(Object) --// passes a connection and checks the type
	if typeof(Object) == "RBXScriptConnection" then
		table.insert(self.Cleanup, function() Object:Disconnect() end)
	elseif typeof(Object) == "Instance" then
		table.insert(self.Cleanup, function() Object.Parent = nil end)
	elseif typeof(Object) == "function" then
		table.insert(self.Cleanup, Object)
	elseif typeof(Object) == "table" and typeof(Object.PlaybackState) == "EnumItem" then
		table.insert(self.Cleanup, function()
			if Object.PlaybackState == Enum.PlaybackState.Playing then Object:Cancel() end
		end)
	end
end

function Janitor:Clean() --// call to clear your janitor connecitons
	for _, Cleanup in ipairs(self.Cleanup) do
		local succes, err = pcall(Cleanup)
		if not succes then warn("Janitor didnt cleanup", err) end
	end
	table.clear(self.Cleanup)
end


return Janitor

i had the same experience you may have, so made this module! let me know if a memory leak happens

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