Optimizing my Tycoon

Hi, im making this post today becuase when my tycoon spawns parts (a lot of parts at a time) it causes a lot of lag and increases the CPU a lot

local Main = require(game.ReplicatedStorage.Framework)
local Action : RemoteEvent = Main:GetElement("Action")

local RunService = game:GetService("RunService")

local OreController = {}

local ConveyorTable = {}
local ActiveOres = {}
local ActiveOreCount = 0

local DefaultSpeed = 20
local RecheckInterval = 0.4

task.spawn(function()
	task.wait(5)
	for _, v in pairs(workspace:GetDescendants()) do
		if v.Name == "DONOTCHANGE" then
			table.insert(ConveyorTable, v)
		end
	end
end)

local function CountActive()
	return ActiveOreCount
end

local function FindConveyor(position)
	local rp = RaycastParams.new()
	rp.FilterType = Enum.RaycastFilterType.Whitelist
	rp.FilterDescendantsInstances = ConveyorTable
	local result = workspace:Raycast(position, Vector3.new(0, -10, 0), rp)
	if result and result.Instance.Name == "DONOTCHANGE" then
		return result.Instance
	end
end

local function GetDirAndSpeed(conveyor)
	local dir = Vector3.new(1,0,0)
	local speed = DefaultSpeed
	if conveyor and conveyor:IsA("BasePart") then
		dir = conveyor.CFrame.RightVector
		local aDir = conveyor:GetAttribute("Direction")
		if typeof(aDir) == "Vector3" and aDir.Magnitude > 0 then dir = aDir.Unit end
		local v3 = conveyor:FindFirstChild("Direction")
		if v3 and v3:IsA("Vector3Value") and v3.Value.Magnitude > 0 then dir = v3.Value.Unit end
		local att = conveyor:FindFirstChild("Dir")
		if att and att:IsA("Attachment") then dir = att.WorldCFrame.LookVector.Unit end
		local aSpeed = conveyor:GetAttribute("Speed")
		if typeof(aSpeed) == "number" then speed = aSpeed end
		local n = conveyor:FindFirstChild("Speed")
		if n and n:IsA("NumberValue") then speed = n.Value end
	end
	return dir, speed
end

local function GetRandomOre()
	local total = 0
	for _, data in pairs(Main:GetClass("OreData")) do
		total += data.Chance
	end
	local roll = math.random() * total
	local cum = 0
	for name, data in pairs(Main:GetClass("OreData")) do
		cum += data.Chance
		if roll <= cum then
			return name
		end
	end
end

RunService.Heartbeat:Connect(function(dt)
	for ore, data in pairs(ActiveOres) do
		if ore and ore.Parent and ore.PrimaryPart then
			data.Timer = (data.Timer or 0) + dt
			if data.Timer >= RecheckInterval then
				data.Timer = 0
				data.Conveyor = FindConveyor(ore.PrimaryPart.Position)
				if data.Conveyor then
					local _, spd = GetDirAndSpeed(data.Conveyor)
					data.Speed = spd
				end
			end
			if data.Conveyor then
				local dir, spd = GetDirAndSpeed(data.Conveyor)
				local step = dir * (spd * dt)
				ore.PrimaryPart.CFrame = ore.PrimaryPart.CFrame + step
			end
		else
			if ActiveOres[ore] then
				ActiveOres[ore] = nil
				ActiveOreCount -= 1
			end
		end
	end
end)

function OreController.Init()
	Action.OnClientEvent:Connect(function(ActionName, DropperArea, Player, tycoonData)
		if ActionName == "MakeOre" then
			if CountActive() >= 300 then return end
			local oreName = tycoonData.SpecialDrill and ("Refined"..GetRandomOre()) or GetRandomOre()
			local Ore = Main:GetElement(oreName):Clone()
			Ore.Parent = workspace.ExistingOres
			Ore:MoveTo(DropperArea.Position - Vector3.new(0, 2.25, 0))
			if Ore:IsA("Model") and not Ore.PrimaryPart then
				Ore.PrimaryPart = Ore:FindFirstChildWhichIsA("BasePart")
			end
			for _, p in ipairs(Ore:GetDescendants()) do
				if p:IsA("BasePart") then
					p.Massless = true
					p.CastShadow = false
					p.CollisionGroup = "Ores"
					p:SetAttribute("Multiplier", 1)
					p:SetAttribute("Size", tycoonData.Size)
					p:SetAttribute("Player", Player.Name)
					if not tycoonData.SpecialDrill then
						p:SetAttribute("IsOre", true)
					else
						p:SetAttribute("IsRefined", true)
					end
				end
			end
			Ore:SetAttribute("Multiplier", 1)
			Ore:SetAttribute("Size", tycoonData.Size)
			Ore:SetAttribute("Player", Player.Name)
			local cv = FindConveyor(Ore.PrimaryPart.Position)
			local _, spd = GetDirAndSpeed(cv)
			ActiveOres[Ore] = {Conveyor = cv, Speed = spd, Timer = 0}
			ActiveOreCount += 1
			Ore.AncestryChanged:Connect(function(_, parent)
				if not parent and ActiveOres[Ore] then
					ActiveOres[Ore] = nil
					ActiveOreCount -= 1
				end
			end)
			task.delay(10, function()
				if Ore and Ore.Parent then Ore:Destroy() end
			end)
		end
	end)
end

return OreController

This is the ore spawning script.
Thanks!

Upon inspection of your script here, there are no obvious flaws I could find that should impact your performance majorly. It’s possible that there is a flaw elsewhere resulting in this performance issue, however, I’ll assume you’ve tested this. While there is a chance that your computer simply is slow, I have a couple things you could consider trying to help performance. It’s entirely possible that these have occurred to you, however I’ll share anyway.

task.spawn(function()
	task.wait(5)
	for _, v in pairs(workspace:GetDescendants()) do
		if v.Name == "DONOTCHANGE" then
			table.insert(ConveyorTable, v)
		end
	end
end)

It’s somewhat unclear why exactly you need instances named “DONOTCHANGE”, however, you should avoid creating a separate thread for this task - it can impact performance (albeit, this shouldn’t cause a massive amount of lag). It shouldn’t be a stretch to achieve this by lookup or an event-based system.

RunService.Heartbeat:Connect(function(dt)
	for ore, data in pairs(ActiveOres) do
		if ore and ore.Parent and ore.PrimaryPart then
			data.Timer = (data.Timer or 0) + dt
			if data.Timer >= RecheckInterval then
				data.Timer = 0
				data.Conveyor = FindConveyor(ore.PrimaryPart.Position)
				if data.Conveyor then
					local _, spd = GetDirAndSpeed(data.Conveyor)
					data.Speed = spd
				end
			end
			if data.Conveyor then
				local dir, spd = GetDirAndSpeed(data.Conveyor)
				local step = dir * (spd * dt)
				ore.PrimaryPart.CFrame = ore.PrimaryPart.CFrame + step
			end
		else
			if ActiveOres[ore] then
				ActiveOres[ore] = nil
				ActiveOreCount -= 1
			end
		end
	end
end)

While I believe this shouldn’t be problematic for you, there are quite a lot of large operation inside of RunService.Heartbeat. If it’s not necessary to run every frame, consider a higher interval.

Then, as for OreController.Init - I’m sure you acknowledge that this is quite an expensive task, however, for a LocalScript, it really should be trivial.

There are some thing you can optimize: Shy away from assigning the PrimaryPart dynamically if unnecessary. Can you reduce the amount of Descendants in an Ore? You spawn a separate thread to destroy the ore 10 seconds after- is there an event-based approach to do this, or iteratively?
As far as it appears, you’re manually changing the position of ore- are the parts anchored?

Like I said, nothing jumps out of the blue, but there are certainly some optimizations you can make.
Let me know if there is any more information you can share to give you a better answer.

Just going to go on a guess and assume you’ve locked it down to this script being the main issue

in that case, the only thing I can think of is the fact that, for every ore you’re spawning in,
you’re doing this entire operation on each one:

if ore and ore.Parent and ore.PrimaryPart then
			data.Timer = (data.Timer or 0) + dt
			if data.Timer >= RecheckInterval then
				data.Timer = 0
				data.Conveyor = FindConveyor(ore.PrimaryPart.Position)
				if data.Conveyor then
					local _, spd = GetDirAndSpeed(data.Conveyor)
					data.Speed = spd
				end
			end
			if data.Conveyor then
				local dir, spd = GetDirAndSpeed(data.Conveyor)
				local step = dir * (spd * dt)
				ore.PrimaryPart.CFrame = ore.PrimaryPart.CFrame + step
			end
		else
			if ActiveOres[ore] then
				ActiveOres[ore] = nil
				ActiveOreCount -= 1
			end
		end

And you’re doing that every heartbeat.
To break it down for 1 ore:
You’re checking if it exists and has the necessary stuff you need
You’re checking the timer on it, if the timer matches, you’re raycasting downward 10 studs
You’re also checking for its magnitude, direction, values, numbers, speed, and returning direction and speed
In addition, you’re also recreating the same raycast params every heartbeat if the ore meets the conditions

So ores only have 1 descendant and the ore controller is initialzed once.

So how would i make the runservice less expensive and efficient
And hundreds of ores are made every 10 seconds

Is it absolutely necessary to run this on Heartbeat?
Consider an approach similar to this:

coroutine.resume(coroutine.create(function()
local timeInterval = .1
while wait(timeInterval) do
	for ore, data in pairs(ActiveOres) do
		if ore and ore.Parent and ore.PrimaryPart then
			data.Timer = (data.Timer or 0) + timeInterval
			if data.Timer >= RecheckInterval then
				data.Timer = 0
				data.Conveyor = FindConveyor(ore.PrimaryPart.Position)
				if data.Conveyor then
					local _, spd = GetDirAndSpeed(data.Conveyor)
					data.Speed = spd
				end
			end
			if data.Conveyor then
				local dir, spd = GetDirAndSpeed(data.Conveyor)
				local step = dir * (spd * timeInterval)
				ore.PrimaryPart.CFrame = ore.PrimaryPart.CFrame + step
			end
		else
			if ActiveOres[ore] then
				ActiveOres[ore] = nil
				ActiveOreCount -= 1
			end
		end
	end
end
end))

Obviously, you’ll need to tweak timeInterval and constants like spd, RecheckInterval for proper functionality likely. If you must run this on Heartbeat- you may need to consider an entirely different approach if it’s truly upto nothing else.

heartbeat event fires every frame so you shouldnt even be using it in this case. you should be wary with using runservice, usually i atleast would have a variable connected to it so you can disconnect the connection like inside of some repeatable code

local connection
connection = RunService.Heartbeat:Connect(function()
    print("something")

    if ... then
        connection:Disconnect()
    end
end)

Add delays in the middle of your ore loop so the CPU isn’t overloaded.

while true do
	local dt = task.wait()
	local i = 0
	
	for ore, data in pairs(ActiveOres) do
		if ore and ore.Parent and ore.PrimaryPart then
			data.Timer = (data.Timer or 0) + dt
			if data.Timer >= RecheckInterval then
				data.Timer = 0
				data.Conveyor = FindConveyor(ore.PrimaryPart.Position)
				if data.Conveyor then
					local _, spd = GetDirAndSpeed(data.Conveyor)
					data.Speed = spd
				end
			end
			if data.Conveyor then
				local dir, spd = GetDirAndSpeed(data.Conveyor)
				local step = dir * (spd * dt)
				ore.PrimaryPart.CFrame = ore.PrimaryPart.CFrame + step
			end
		else
			if ActiveOres[ore] then
				ActiveOres[ore] = nil
				ActiveOreCount -= 1
			end
		end
		
		i += 1
		
		if i % 20 == 0 then
			dt += task.wait()
		end
	end
end