Hello! Just a basic query, I’m running a purely cosmetic script for the Local player that utilizes the Heartbeat function to, well, do something every frame and I have another functionally identical script that does that same thing but for NPCs (locally).
Considering they’re less important than the player themselves, I didn’t want them using a purely cosmetic script that runs every frame if it was eating up resources, so I thought maybe utilizing a while true loop with a decreased frequency (say like task.wait(1)) would be more resource efficient, yet every discussion I read says a while true loop is going to be less efficient regardless.
Is this true, I’m skeptical? should I just be running the script every frame anyway? why is it like this?
If effects visibly break without per frame updates, use RunService options. Otherwise, prefer lower frequency updates to reduce cost.
task.wait(1) .. will naturally be less demanding due to the pause..
As long as what you are running isn’t very costly then you shouldn’t have to worry about running it every frame as it won’t be very resource intensive.
You could have Heartbeat run every second like this example.
local RunService = game:GetService("RunService")
local INTERVAL = 2 --in seconds, 2 in this case.
local t = 0
RunService.Heartbeat:Connect(function(dt)
t += dt
if t < INTERVAL then
return --Skip frame
end
t = 0
--Do your thing here.
end)
Then again you do not really have to worry about the costs of loops, in my experience its what you do in the loop that matters and even then it usually isn’t that costly.
I actually went ahead and stress tested it myself using about 32 NPCs and both of the above methods seemed to improve performance, thank you both!! The most efficient for me personally was the interval-ed Heartbeat so I went ahead with that one. But both work great!!