While true Vs RunService Performance

Is using a while true do or using RunService better for performance?

I would assume it is while true do loop as it doesn’t fire every frame however, I could be wrong. Note: I understand the difference in each method however, strictly speaking, which one is better for performance.

1 Like

A while true do loop runs repeatedly until you break it. Listening to RunService.Heartbeat runs something every frame. They are completely different, so you’ll have to explain more about what you’re doing.

This code:

local previousTime = tick()
while true do
    local currentTime = tick()
    model:TranslateBy(Vector3.new(0, 2 * (currentTime - previousTime), 0))
    previousTime = currentTime
end

Will not smoothly animate the model. It will crash your script after about 30 seconds because you are never pausing your script for other scripts to run.

This code, however:

RunService.Heartbeat:Connect(function(timePassed)
    model:TranslateBy(Vector3.new(0, 2 * timePassed))
end)

Will move the model up at a rate of 2 studs per second. Note that this code is basically identical to:

while true do
    local timePassed = RunService.Heartbeat:Wait()
    model:TranslateBy(Vector3.new(0, 2 * timePassed))
end

Which is identical to:

while true do
    local timePassed = task.wait()
    model:TranslateBy(Vector3.new(0, 2 * timePassed))
end
1 Like

it really depends on the use case here,
each should be used depending on what you need
so you can’t really compare “performance” between them

Replying to:


For example, if I had a bobbing animation, in terms of performance which one would be better (I understand that RunService would give a smoother result):

while task.wait() do
	Part.Position = Vector3.new(0, math.sin(tick()), 0)
end
game:GetService("RunService").Heartbeat:Connect(function()
	Part.Position = Vector3.new(0, math.sin(tick()), 0)
end)

They are equivalent in terms of smoothness and performance. task.wait() is equivalent to RunService.Heartbeat:Wait().

For readability, I would recommend:

while true do
    task.wait()
    Part.Position = Vector3.new(0, math.sin(tick()), 0)
end

But you don’t have to.

for a bobbinh animations,
run service is the way to go, since it runs every frame
which grants a smoother feel

So both while true and RunService Yeilds the same results in terms of Performance?

I understand that however, which one is better for Performance if we were to ignore the smoother feel

Yes. They do literally the same thing.

1 Like

Okay, thanks for the information!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.