Is while wait loop or runservice heartbeat more stressful on the server?

I am wondering if running a while wait loop on the server in a server script is better or worse in terms of performance than running a runservice heartbeat on the server in a server script. If anyone understands this performance stuff please help me understand, also I will be deleting soon.

While true do

    print("Looped")
end

Or in terms of performance on the server

Runservice.HeartBeat:Connect(function()

    print("Signaled")
end)
1 Like

Well, I believe their performance is about equal, however a while true loop will tend to limit you to only running every other update (wait lowest val), and a heartbeat loop wont. However, the heartbeat event creates a seperate thread every time the event is fired, so the best way to reduce threads and keep it fast is as such:

while RunService.HeartBeat:Wait() do

end

This way, you’re only using 1 thread and rather just listening to it.

7 Likes

while wait() do and while task.wait() do both give the active thread a moment to yield & pause current operations.

No don’t. Roblox is an event based game engine. Roblox uses green threading meaning the overhead between switching threads is minimal, and about the same as having to resume the thread waiting for heartbeat.

You should use :Connect as it is more obvious how the code is invoked.
Optimise for readability first, then performance.

local RunService = game:GetService("RunService")

function PrintMoney()
    print("money")
end

-- function() does not tell us anything about what the code does
-- "PrintMoney" does
RunService.Heartbeat:Connect(PrintMoney) 
4 Likes

You could just create a new coroutine for the while loop itself, by either wrapping it or using the task library (task.spawn, task.defer) to entirely run it in a seperate psyedo-thread where yielding wont matter which would be better than creating infinite psyedo-threads and then resuming them and chainging their state. That might impact the server performance itself

the heartbeat event creates a seperate thread every time the event is fired

Can you please provide a source for this claim?

Otherwise, the heartbeat event would act like a while loop, right?

local RunService = game:GetService("RunService")

RunService.Heartbeat:Connect(function(dT) 
print(dT)
task.wait(5)
end)

-- There is no 5-second delay between each print, dT is printed on each frame.
1 Like

when it comes to RunService.Heartbeat connections, I always just have a debounce just in case the event is again before the previously fired event can run. When I dont want to connect smth directly to the RunService Heartbeat I use a repeat local DeltaTime: number = RunService.Heartbeat:Wait() until Toggle == false. Then Toggle is just a boolean I can access so that I can “disconnect” the function. This is my alternative to creating a boolean for my heartbeat functions