Tween Instance Question

Hi! I use TweenService practically all the time but in this context for what I’ve been using it for recently, I’ve been using it to create “mesh particles.” Which means I’m creating many tween instances to give a particle-like effect. And to enhance game performance, I’ve been reading about the impact or troubles associated with creating many tween instances without closing them and have found mixed opinions. Firstly, is it necessary to close tween instances once they’ve finished, and is it problematic if the object the tween is acting on is destroyed in the middle of the tweening?
Lastly, this is a little helper function for destroying a block by first giving it a disappearing effect:

local function destroyBlockDo(block: part): nil
	local tween = tweenService:Create(block, TweenInfo.new(10, Enum.EasingStyle.Linear), 
		{Transparency = 1});
	tween.Completed:Once(function() block:Destroy(); end);
	tween:Play();
end

will this cause a memory leak, and if so why?

Many thanks! : )

You don’t need to clean it up because the garbage collector will deal with that for you. You can see it your self in the console.

not destroying the tween:

destroying the tween:

2 Likes
debug.setmemorycategory("TweenTesting")

local TweenService = game:GetService("TweenService")
local Workspace = game:GetService("Workspace")

local function destroyBlockDo(block: part): nil
	local tween = TweenService:Create(block, TweenInfo.new(10, Enum.EasingStyle.Linear), 
		{Transparency = 1});
	tween.Completed:Once(function() block:Destroy(); 	tween:Destroy(); end);
	tween:Play();
end

task.wait(16)
print("yes destroying tween")

for _, part in Workspace:GetChildren() do
	if part.Name ~= "Part" or not part:IsA("BasePart") then
		continue
	end
	destroyBlockDo(part)
end

Oh wait I did the test wrong but as you can see here they end up being the same if you delete the tween or not:

Not deleting tween:

Deleting tween:

1 Like

Neat that’s nice to hear (definitely need to start using the developer console more often as well lol)! But for my other question:

The way the function is structured won’t cause a memory leak because of the fact that tween instances are collected as well as how once the function ends, there will no longer be a reference to the created tween instance via the “tween” variable right? Many thanks! : )

As is the case with any signal, on any instance, the otherwise unreferenced nil parented instance will only persist in memory, if it forms a cyclic reference with itself through its connections.

-- Tween does not need to be destroyed in this case
Tween.Completed:Once(function()
	Block:Destroy()
end)
-- Tween does need to be destroyed in this case,
-- as the connected function's closure holds a reference back to the Tween instance
-- and the unclosed connection persists the function.
Tween.Completed:Connect(function()
	print(Tween)
end)