How to reduce lag spikes when using :Clone() for multiple UI templates?

  1. What do you want to achieve? Keep it simple and clear!
    I am trying to create a smooth Gacha rolling system similar to popular anime games. The system should roll through approximately 50 items using a ScrollingFrame and TweenService to animate the CanvasPosition

  2. What is the issue? Include screenshots / videos if possible!
    Whenever the Roll function is triggered, there is a massive lag spike (frame drop). I’ve identified that the bottleneck happens when the script prepares the 50 templates inside the ScrollingFrame

  3. What solutions have you tried so far? Did you look for solutions on the Creator Hub?
    I’m currently out of ideas on how to optimize this further

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

-- // CORE
local Core = require(game.Players.LocalPlayer.PlayerScripts.ClientCore.Start.Core)

local EnumTypesItems = require(game.ReplicatedStorage.GameCore.Modules.Informations.Enums.EnumTypesItems)

-- // Services
local TweenService = game:GetService("TweenService")
local Player = game:GetService("Players").LocalPlayer

-- // Elements
local PlayerGui = Core.Player.Instance:WaitForChild("PlayerGui")
local Main: ScreenGui = PlayerGui:WaitForChild("Paradox")
local GachaRolls: Frame = Main:WaitForChild("GachaRolls")

-- // Variables
local Janitor = Core.Shared.Janitor.new()

-- // Private Functions

-- // Animations
return table.freeze({
	["Roll"] = function(...)
		local started = tick()
		Player:SetAttribute("Rolling", true)
		-- Cleanup
		Janitor:Cleanup()
		
		-- Variables
		local Data = (...)
		if not Data then warn("no data foujnd") return end
		
		local GachaData = Data.Gacha and Core.Shared.GachasItens:GetGacha(Data.Gacha) or Core.Shared.warriorsGacha[Data.WarriorWorld]
		local isWarrior = Data.WarriorWorld ~= nil

		-- Functions
		local function CreateTemplate(Roll: Frame, Quantity: number, RandomGacha: boolean, Template: string)
			local createdTemplates = {}

			for i = 1, Quantity do
				local Title: string, Data: {}
				if RandomGacha then
					Title, Data = Core.Shared.GachasItens:GetRandomItem(GachaData.Gacha)
				else
					Title = Template
					Data = GachaData.Gacha[Template]
				end
				
				local TemplateClone: Frame = Roll.ScrollingFrame.Template:Clone()
				TemplateClone.Name = Title
				TemplateClone.Parent = Roll.ScrollingFrame
				TemplateClone.Visible = true
				TemplateClone.Chance.Text = Data.Chance .. "%"
				TemplateClone.ItemName.Text = Title
				TemplateClone:SetAttribute("Title", Title)

				if not isWarrior then
					TemplateClone.Icon.Image = Data.Icon
					TemplateClone:FindFirstChild(Data.Rarity).Enabled = true
				else
					local warriorData = Core.Shared.WarriorsData[Title]
					if not warriorData then warn("NO DATA FOUND??", Title) continue end

					TemplateClone:FindFirstChild(warriorData.Rarity).Enabled = true
					TemplateClone.Icon.Visible = false

					table.insert(createdTemplates, TemplateClone)
				end

				if not RandomGacha then
					if isWarrior then
						task.spawn(function()
							game.RunService.Heartbeat:Wait()
							Core.Utils.GetTypeIVForItem:GetTypeIVForItem(TemplateClone.ViewportFrame, TemplateClone.Icon, Title, EnumTypesItems.WARRIOR)
						end)
					end
					return TemplateClone
				end

				Janitor:Add(TemplateClone, "Destroy")
			end

			if isWarrior and #createdTemplates > 0 then
				task.spawn(function()
					for _, template in createdTemplates do
						if not template.Parent then continue end 

						game.RunService.Heartbeat:Wait()

						local title = template:GetAttribute("Title")
						Core.Utils.GetTypeIVForItem:GetTypeIVForItem(template.ViewportFrame, template.Icon, title, EnumTypesItems.WARRIOR)
					end
				end)
			end
		end

		-- Animate
		local Tween
		for _, Data in ipairs(Data.Rewards) do
			local TemplateRoll: Frame = GachaRolls.Template:Clone()
			TemplateRoll.Name = "Roll"
			TemplateRoll.Parent = GachaRolls
			TemplateRoll.Visible = true
			
			Janitor:Add(TemplateRoll, "Destroy")

			-- Creating Templates
			CreateTemplate(TemplateRoll, 40, true)
			local TemplateTrue: ImageButton = CreateTemplate(TemplateRoll, 1, false, Data.Reward)
			CreateTemplate(TemplateRoll, 9 , true)
			
			-- Calculate X Pos absolutepos - scrolling absolutepos / 2 + template size / 2
			local X: number = TemplateTrue.AbsolutePosition.X - TemplateRoll.ScrollingFrame.AbsolutePosition.X - (TemplateRoll.ScrollingFrame.AbsoluteWindowSize.X / 2) + (TemplateTrue.AbsoluteSize.X / 2)
			--print(X)
			--print(TemplateTrue.AbsolutePosition.X - TemplateRoll.ScrollingFrame.AbsolutePosition.X)
			
			-- Tweening Scrolling
			Tween = TweenService:Create(TemplateRoll.ScrollingFrame, TweenInfo.new(4, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), { CanvasPosition = Vector2.new(X, 0) })
			Tween:Play()
			
			Core.Managers.SoundManager:PlayUI("GachaRoll")
		end
		
		Core.UI.UIController:HUD(false, true)
		Core.UI.UIController:ToggleUI(false, true)
		
		GachaRolls.Visible = true
		
		Tween.Completed:Wait()
		
		local function finish()
			Core.UI.UIController:ToggleUI(true, false)

			if Core.UI.UIController.IsHUDToggled then
				Core.UI.UIController:HUD(true, false)
			else
				Core.UI.UIController:HUD(false, false)
			end
		end
		
		if not Player:GetAttribute("Auto_Gacha") then
			GachaRolls.Visible = false

			finish()
		else
			finish()
		end
		
		Player:SetAttribute("Rolling", false)
	end,
})

Instead of cloning all of the items just clone the required frames and reuse them for instance clone 10 and chang their image and position once it’s no longer visible and repeat

Rather that destroying the frames and then remaking them you could create a separate cache for them and pool the objects.

local GachaRollTemplate: Instance = ...
local TemplatePool: {Instance} = {}

local function GetGachaRoll(): Frame
    -- Returns an instance from the pool or creates one if none exists
    return table.remove(TemplatePool) or GachaRollTemplate:Clone()
end

-- just implement something like this wherever you create your templates
for i = 1, 50 do
    local Clone: Frame = GetGachaRoll()
    -- Your code to do stuff here
    -- ...
    
    -- Idk how your janitor object works, I assume its some kinda maid
    Janitor:Add(function()
        -- Remove from UI BUT NOT DESTROY
        Clone.Parent = nil

        -- Return to cache
        table.insert(TemplatePool, Clone)
    end)
end

This will still lag the first time, but every subsequent time It should be much faster however. If you want to avoid the initial lag spike, what you could do is load some templates initially.

If initial load times is a problem I recommend staggering it by loading only a few templates per frame until the target amount is reached in the background (could cause initial fps drop but otherwise fine).

Naive approach (just to get you started)

local GachaRollTemplate: Instance = ...
local TemplatePool: {Instance} = {}

local function GetGachaRoll(): Frame
    -- Returns an instance from the pool or creates one if none exists
    return table.remove(TemplatePool) or GachaRollTemplate:Clone()
end

-- Caches some templates for better run-time performance
local function CacheAsync()
    for i = 1, 50 do
        table.insert(TemplatePool, GachaRollTemplate:Clone())
        if i % 4 == 0 then task.wait() end -- waits till the next frame every 4 clones
    end
end

-- In your bootstrapping code (or wherever, doesnt really matter)
task.spawn(CacheAsync)
-- task.spawn in because it yields and we don't want to stop the main thread. 
-- So now it fills the pool in a separate thread (but still serial and may still lower frames somewhat)

Let me know if you need any other help or if something was unclear.

Thanks a lot for the tip! This is going to be really useful :grinning_face_with_smiling_eyes:

No worries :wink: Good luck and most importantly have fun