In C#, when setting a boolean variable’s value to false only when it is true, should I check if it is true before setting it or just set it?
Assuming the variable is true 50% of the time, checking it makes sense since a comparison is faster. If the variable is true most of the time, should I just skip the comparison?
Which is the better practice?
Method 1, checking first:
if (bVariable)
bVariable = false;
or Method 2, Just setting it:
bVariable = false;
Under which conditions is method 2 preferred, if ever?
What makes you think that the comparison is faster? If the code you were writing was done in a C compiler, the IF statement would be split into at least two instructions — a comparison/branching instruction and a “set” instruction on a single bit on a single word.
The “set” would compile to a single instruction. Your “optimization” could possibly make your program run slower, and would cause your program to be less readable. Just set the variable and don’t try to overthink little things.
CPUs aren’t like databases. You don’t pay a high penalty for data modifications. You pay high penalties for making trips to main memory and for branching (if statements). Branches cost performance because pipelining CPUs actually start executing instructions after the branch before the branch instructions even make their decision! (I know, that statement is somewhat mind-blowing). But what that means is that the CPU has to spend resources “guessing” what the outcome of your IF statement is going to be. If it guesses wrong, it has to “throw away” the results of all instructions that it guessed would be executed after the branch and try again. It’s bad. It’s why branches are expensive.
The moral of this particular story is not that you should never optimize, but that you should never optimize without completely understanding the implications of your optimization. In this case, had you gone with Option 1, you could possibly end up with a slower app which is less readable to boot.
Actually, if you’re really interested in this sort of thing, you should definitely pick up a copy of Code Complete. It’s full of discussions about this sort of thing, and is brilliantly written.