I don't know if this part caching module needs some optimization, any clean up required?

I’m creating a fighting game. I made this quick cache system because of the supposed performance difference between changing a CFrame and Instance.new/Clone().

I’m fine with it as is, and it has gone through testing, I just want to confirm that it won’t generate any memory leaks. I expect servers to be as much as 24 hours old in a lot of cases.

module:Destroy() is the clean-up function.

The module:
local replicatedStorage = game:GetService("ReplicatedStorage")

local SkillService = replicatedStorage:WaitForChild("SkillService")
local cacheParent = workspace:WaitForChild("Skills")

local module = {}
module.__index = module

--creates a new cache for this player
function module.new(Player)
	local mt = {}
	
	local cacheFolder = Instance.new("Folder")
	cacheFolder.Name = Player.Name
	cacheFolder.Parent = cacheParent
	
	mt.Cache = cacheFolder
	return setmetatable(module, mt)
end
--

function module:Generate(Ability) --create player's cache
	local skillList = SkillService:FindFirstChild(Ability):WaitForChild("Models")
	
	for _, Model in pairs(skillList:GetChildren()) do
		local cachedModel = Model:Clone()
		cachedModel.Parent = self.Cache
	end
end

function module:Clear() --mainly for when they switch abilities
	self.Cache:ClearAllChildren()
end

function module:Destroy() --destroy the cache
	self.Cache:Destroy()
end

return module

Calling :Destroy() is not enough, you also need to set it to nil

1 Like

Set what to nil? From what I was aware, instances such as folders (self.Cache) were set to nil upon :Destroy()?

From the devhub Instance | Roblox Creator Documentation

local part = Instance.new("Part")
part.Name = "Hello, world"
part:Destroy()
-- Don't do this:
print(part.Name) --> "Hello, world"
-- Do this to prevent the above line from working:
part = nil
1 Like

Thank you so much! I didn’t know about this.

1 Like