Instance Pooling

Why pool instances?
Instance.new is slow.

When should I pool instances?
When you find yourself creating large amounts of instances after the game has loaded. I’d say up to 100 is fine.

Why not PartCache?
This is probably faster (not tested) and it allows pooling other classes, such as GUIs, which I found highly useful when I am doing fractals.

Documentation is available as comments at the top.
For those who like to experiment and learn from example:

local InstancePool = require(path.to.the.module)
local PartPool

--// scope function references
do
	local CreatePart = function()
		local Part = Instance.new("Part")
		Part.Anchored = true
		Part.CFrame = CFrame.new(1e9,2e9,3e9)

		return Part
	end

	local FunctionCalledWhenTheInstanceIsReturned = function(Part)
		Part.CFrame = CFrame.new(1e9,2e9,3e9)
	end

	PartPool = InstancePool.new(1000, CreatePart, FunctionCalledWhenTheInstanceIsReturned)
end

--// EPICCC skript to make rainbow towarr with gaps :P
local a = 0
for i = 0, 50*2*math.pi, 50*2*math.pi/2000 do
	local P = PartPool:Get()
	P.CFrame = CFrame.lookAt(Vector3.new(24.366666*math.cos(i), i, 24.366666*math.sin(i)), Vector3.new(0,i,0))

	--local i1=a%7
	--local i2=i1*i1
	--local i3=i2*i1
	--local i4=i3*i1
	--local i5=i4*i1
	--local i6=i5*i1

	--P.Color=Color3.new(.012244*i6-.231209*i5+1.64123*i4-5.33578*i3+7.60731*i2-3.69379*i1+1,.00973856*i6-.166993*i5+1.07892*i4-3.25948*i3+4.43095*i2-1.5951*i1,.0177342*i6-3.03431*i5+1.963626*i4-5.54984*i3+7.18842*i2-3.27614*i1)

	if bit32.band(a, 0x7F) == 0 then
		PartPool:Return(P)
	end

	a = a + 1
end

--for _, v in next, workspace.Folder:GetChildren() do
--	PartPool:Return(v)
--end
--// equivalent to PartPool:MassReturn(workspace.Folder:GetChildren()), except a bit slower.

PartPool:Destroy() --// Destroy all the instances in the pool. Use only when you don't need it anymore.

Note:
DO NOT RETURN THE SAME INSTANCE TWICE BEFORE GETTING IT. THIS WILL LEAD TO VERY BAD MEMORY LEAK.

As a lazy fix, you can use a table and store the instances that you got, and :MassReturn the array, then set the table to nil. (there is some GC overhead with this tho)

Link

10 Likes

Wow! This is a great resource. I 100% need this and I can’t live without it. Thanks for providing high quality resources for me and roblox.