[Solved]Optimizating code?

I have some variables that must be updated almost every frame, and was wondering which would be the best way to update them:

In this example, when the bool “whatever” is “true”, bool “sampleBool” is set to “true”, float “randomFloat” is set to “3”, and GameObject “someGameObject” is set to “null”.

  • bool “whatever” may remain “true” for more than 1 frame.

standard-Issue simple change:

void Update() {
       if (whatever == true) {
                sampleBool = true;
                randomFloat = 3;
                someGameObject = null;
       }
}

using if statements to check if they are already like the desired:

void Update() {
       if (whatever == true) {
                if (!sampleBool) { sampleBool = true; }
                if (randomFloat != 3) { randomFloat = 3; }
                if (someGameObject != null) { someGameObject = null; }
       }
}

or using another bool for it to only run once:

void Update() {
       if (whatever == true && anotherBool == false) {
                sampleBool = true;
                randomFloat = 3;
                someGameObject = null;
                anotherBool = true;
       }
}

Or are all of these have the same performace impact? (Which is very unlikely)

Thanks in advance.

this is just premature optimization, but i would assume providing these members you are setting are fields and not properties that the solution that uses the least amount of conditional would be cheapest.

But there is no need to even think about optimizing on this level, till you have identified that you have a performance problem, and where the issue is coming from.

5 Likes

This. There is no way you are right enough that shaving a fraction of a millisecond every minute here will make a difference to your overall performance.

But for the record the fastest way to do this will be through a property on whatever. That way the other variable will only be updated if whatever changes.

4 Likes

Whichever method is the most easily understood by you. Because when you come back to your project to correct a bug or add a new feature you’ll want to make the process as painless as possible. Unless the profiler says you’re spending entirely too much time processing those variables (you’d have to be on a Commodore VIC-20 for this to be a problem) you simply don’t have to optimize them.

1 Like

I suppose you could also be running this script on ten million GameObjects. In which case you would have a different set of ways to optimize.

Well then, good to know it almost makes no difference.