Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Can certain loops cause lag inefficiency to your game?

A while ago a user told me that using while loops could cause your game to lag and that it is inefficient. Which code would be better to use?

.Changed:connect(function()
if Value == true then
print("Hi")
end
end)

OR

while wait() do
if Value == true then
print("Hi")
end
end

3 answers

✓ Accepted answer

In a situation like this, the first option is always going to be the best option.

The second option uses a while loop that constantly checks if the value is true. This uses up resources because you're looping 1/30th a second as well as checking if a value is true.

On the other hand, the first option uses an event which fires when the value is changed. You don't need to constantly check all the time, you just need to check when it changes.

Here's an analogy:

There's a guest coming around to your house. Are you going to constantly check the door if he/she is there while you could be preparing the house or food, etc? Or will you prepare the house/food, while waiting for the doorbell to be rang?

There's a doorbell for a reason.

1 comment

0

Love this example, nice.

Unless the player has a terrible PC these will have near to no impact, it is probably better to run it as the property changes (the first code you put). This is because it's much more efficient to check something when it needs to instead of all the time.

Yes just think of it like this.

You get a cat everytime you say hi. With a while loop it says hi almost instantanously no matter if theres a value it still has to check to see if that value was there

With an event it saves cpu because it onylu fires when something happens.

3 comments

0

Lol I like the explaination but let's be realistic here.. did the rest of that have anything to do with a cat? Lol, I'm going to thumbs you up though.

0

Upvote*

1

yes it was the most needed aspect.

This discussion is preserved as it was. New answers, comments, and votes are closed.