So I have this below. If I am doing an operation like this is it generally considered a good practice to “gate” the variable assignment with an if to avoid just continually assigning that variable while in the loop?
while (isMoving) {
ATBgov.ATBspeed = loweredSpeed;
yield return null;
}
Would it be better to add a line in there below?
if (ATBgov.ATBspeed != loweredSpeed) ATBgov.ATBspeed = loweredSpeed;
General rule of optimization: do not optimize if you’re not having performance problems. If you’re having performance problem, then figure out where and then fix it instead of optimizing everything.
NOTE: YOU CANNOT COMPARE FLOATS TO FLOATS SAFELY AS WAS DONE IN THE QUESTION
THIS IS A GENERAL ANSWER THAT IF STATEMENTS ARE BETTER. FLOATS SHOULDNT BE IN IF STATEMENT COMPARISIONS SO IT DOESN’T APPLY.
Yes its good practice.
Checks have a pretty low impact.
Things inside the if statements will at best probably be as efficient.
If that assignment was…
copying one array to another
finding a game object in a scene
calling a component through getcomponent
etc
You’d want to avoid doing those every frame, copying a hundred array variables 50 times a second is way slower than doing an if check 50 times.
Since almost nothing is faster than a if checks you if check.