While loops vs changed events

Alright, imagine if I had a game named White Space - Roblox.

When the player enters the game, their screen would literally be white everywhere, no floors, no walls, and it would be just a limitless space where you can technically walk forever.

where you can walk forever

I would achieve above by putting a small invisible platform below the player, and use while loops to reposition the platform to below the player for every loop.

That got me thinking, this below is what I would be using for the script:

while task.wait() do
   --reposition the platform to below the player
end

but there’s also this option that should work too:

hrp.Changed:Connect(function()
   --reposition the platform to below the player
end)

Which of the codes above would be more performant if I were to use it to reposition my platform to below the player?

While will probably be more reliable in this scenario.

Rather than every frame, you could just make a large transparent platform that repositions every 5-10 seconds.

High frequency part moving is only really useful for parkour and bullet projectile scripts

1 Like

Changes in the values of physics related properties of an instance don’t fire the “.Changed” event for that instance.

Consider using an event loop like “.RenderStepped” as this can all be handled locally.

2 Likes

That sounds perfect, thank you!

I know this has already been solved however,

while true do
  task.wait()
end

has better performance than

while task.wait() do

end

This is because Lua has an optimisation where if a loop’s condition is the true keyword, Lua will continue the while loop without running a conditional check on the loop, unless there is a break call

5 Likes

That’s super good to know too, thank you, just wanna get the performance up especially with my bad pc

Also adding something here even though it’s been solved: please don’t use RenderStepped for anything except the camera or updating a property of the character (i.e. LocalTransparencyModifier of parts in them or a CFrame property). Go with Heartbeat instead.

Running expensive code in RenderStepped can result in slowed render execution because RenderStepped needs to complete before a frame renders. In nearly all cases of using RunService you should be using Heartbeat. You can use Stepped if your computations need to happen before physics get simulated and RenderStepped if and only if you need something to happen before the frame renders and there are a rare number of scenarios where that case is ever met.

2 Likes