Petrus Theron
Petrus Theron

Reputation: 28807

Comparing a boolean value before setting it

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?

Upvotes: 13

Views: 3950

Answers (9)

Dave Markle
Dave Markle

Reputation: 97671

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.

Upvotes: 10

Marcelo Cantos
Marcelo Cantos

Reputation: 185842

Don't complicate life. Just set it. It's actually more expensive to check first, anyway, since you now have to slurp the existing value from RAM (or cache) before sending back a new value.

(With thanks to Colin Mackay...) Testing first also incurs pipeline stall penalties due to branch mis-predictions.

Upvotes: 3

PeterT
PeterT

Reputation: 1464

Method 2 should be preferred simply because it expresses the same outcome more simply, making it easier to read, as others have said - for something simple like this legibility is far more important than the vanishingly small performance concern.

However, it is possible that bVariable could be a property, in which case setting it could entail other side-effects - both in terms of performance and outcome, potentially.

Upvotes: 1

Gorpik
Gorpik

Reputation: 11028

In C# the answer is: method 2 is always preferred. Since this is a very simple optimisation, if method 1 were really faster, the compiler would do it.

EDIT:

Donald Knuth has some advice against your method 1, such as "premature optimization is the root of all evil" and "code is meant to be read by humans first, and machines second".

Upvotes: 3

Thomas Weller
Thomas Weller

Reputation: 11717

The performance issue is not relevant here, because a simple if statement like the above essentially is close to a no-op for the processor. It is much more important that your code is clearly communicating its intention for later readers!

Thomas

Upvotes: 0

Colin Mackay
Colin Mackay

Reputation: 19175

I'd say the performance difference is so insignificant just set the thing to false all the time.

If it is false, it will be set to false again. If it is true, it will be set to false.

At the end of the code the variable will be false regardless.

By just setting it to false all the time you make the intent clearer anyway. Anyone else reading the code will instantly see that the value will be false in all instances by the end of that section of code. While if you have an if statement they will have to think about it a little harder.

For maintenance alone, I would advocate setting the value to false regardless of its original value since it will always be false at the end.

Upvotes: 1

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132984

Premature optimization is the root of all evil. There is no way you can persuade me that this "optimization" will give you any performance gain at all

Upvotes: 0

MAK
MAK

Reputation: 26586

This seems like too much of a micro-optimization, I really think the compiler optimizes this bit for you anyway.

But, if you want the final value to be false no matter what, I guess simply assigning it to false makes more sense. I mean why check if you don't really need to care about the value anyway.

Upvotes: 1

Pieter van Ginkel
Pieter van Ginkel

Reputation: 29632

The only reason to do the comparison is if you have extra logic you need to execute when the value changes.

If you are only going to assign it anyway, it will most likely hurt performance if you do the extra check.

Upvotes: 0

Related Questions