Is running the same code in a while loop multiple times expensive or not?

I am currently scripting an AI monster, I am using a while loop to check multiple if statements over and over again when the game is playing. I ran a test to see what happens if I put a print statement in the if statements wrapped by the while loop, and when the if statements condition is true the print statement prints multiple times. This means anything inside that if statement wrapped by a while loop is going to run multiple times which is concerning. I only need these if statements to run the code one time. A big question of mine is whether or not it costs anything to run the same code over and over, whether that be setting a bool to false over and over or an int to the number 10 for example. I do not know much about memory and performance. Also, does .Changed run a while loop to check if values have changed?

Thanks.

local ABool = false
local IsThatBool = nil

while true do
    wait()
    if ABool == true then
        IsThatBool = true
    else
        IsThatBool = false
    end
end


you can change this to

else

also we have signal events for a reason, what exactly do you want to check with the if statements

there could be a better way then while loops depending on what you are checking

Is .changed a signal event? I am trying to check the closest player character in workspace. I know how to do this, the question I need answered is if setting a variable’s value multiple times as the same value in a while loop costs anything?

Instance.Changed:Connect()

yea it is

why are you setting it as the same value over and over, can I see the code?

1 Like

I do not need help with the script, all I need to know is if setting a variables value multiple times costs anything. I just want to make sure whatever I do is not too expensive. The thing is I know how to change it my script so I am not running it multiple times, I just don’t know if it is necessary in terms of performance.

I don’t think it is too bad on performance, you should be fine

but if you can find a more efficient way I would do that

Are you sure? Just to be clear, it is costly to set a variable’s value multiple times even if you are setting the same value over and over right?

Thanks btw for the help, appreciate it.

not really, I don’t know how many things you are changing/how fast you are changing them

I don’t even know if these are Instance.Value changes

1 Like

Okay well thanks for trying anyway!

no problem, I hope your AI goes well

1 Like