How can I optimize this script?

Hello, I have a script which will make coins spin. The problem is, it takes up some performance, on the ‘Script Performance Activity’ the activity is around 6. I have heard that the activity goes above 3% the performance can be impacted.

Here is my code, I know it is not the best. (The script is old by the way.)

local References = require(game:GetService("ReplicatedStorage").Utilities.Services.References)
local Utilities = References.Utilities
local Services = Utilities.Services

local CollectionService = Services.Collections
local ReplicatedStorage = Services.Replicated

local currentMap = ReplicatedStorage.Values.CurrentMap

local connections = {}

local function spinCoin(part)
	coroutine.wrap(function()
		local connection = game:GetService("RunService").Heartbeat:Connect(function()
			part.CFrame = part.CFrame * CFrame.fromEulerAnglesXYZ(0.1, 0, 0)
		end)
		connections[part] = connection
	end)()
end

CollectionService:GetInstanceAddedSignal("Coin"):Connect(function(instance)
	spinCoin(instance)
end)

CollectionService:GetInstanceRemovedSignal("Coin"):Connect(function(instance)
	if connections[instance] then
		connections[instance]:Disconnect()
	end
end)

I think the reason is because it is making the coins spin every second, but let me know if there is any possible way to optimize this script or remake it/change it.

Thanks.

Instead of each coin having it’s own connection to Hearbeat, you should connect to it once and loop over the coins.

local coins = {}

game:GetService("RunService").Heartbeat:Connect(function ()
	for _, coin in ipairs(coins) do
		-- Spin coin
		part.CFrame = part.CFrame * CFrame.fromEulerAnglesXYZ(0.1, 0, 0)
	end
end)

CollectionService:GetInstanceAddedSignal("Coin"):Connect(function(instance)
	table.insert(coins, instance)
end)

CollectionService:GetInstanceRemovedSignal("Coin"):Connect(function(instance)
	table.remove(coins, table.find(instance))
end)

The coroutine doesn’t seem to be doing anything either.

2 Likes

Thank you, @FarFromLittle. I do not know why I put a coroutine, also I do not know why I didn’t just loop through them.

Glad to help, and if you are truly concerned about connections left hanging (for example, when no coins exist), you could do something about that too. Not that it means much in this example.

local conn
local coins = {}

local function spinCoins()
	for _, coin in ipairs(coins) do
		part.CFrame = part.CFrame * CFrame.fromEulerAnglesXYZ(0.1, 0, 0)
	end
end)

CollectionService:GetInstanceAddedSignal("Coin"):Connect(function(instance)
	table.insert(coins, instance)
	if #coins == 1 then
		game:GetService("RunService").Heartbeat:Connect(spinCoins)
	end
end)

CollectionService:GetInstanceRemovedSignal("Coin"):Connect(function(instance)
	table.remove(coins, table.find(instance))
	if #coins == 0 then
		conn:Disconnect()
	end
end)
4 Likes