I have code in my C++ application that generally does this:
bool myFlag = false;
while (/*some finite condition unrelated to myFlag*/) {
if (...) {
// statements, unrelated to myFlag
} else {
// set myFlag to true, perhaps only if it was false before?
}
}
if (myFlag) {
// Do something...
}
The question I have pertains to the else
statement of my code. Basically, my loop may set the value of myFlag from false to true, based on a certain condition not being met. Never will the flag be unset from true to false. I would like to know what statement makes more sense performance-wise and perhaps if this issue is actually a non-issue due to compiler optimization.
myFlag = true;
OR
if (!myFlag) myFlag = true;
I would normally choose the former because it requires writing less code. However, I began to wonder that maybe it involved needless writing to memory and therefore the latter would prevent needless writing if myFlag was already true. But, would using the latter take more time because there is a conditional statement and therefore compile code using more instructions?
Or maybe I am over-thinking this too much...
Just to clarify a bit...the purpose of my latter case is to not write to memory if the variable was already true. Thus, only write to memory if the variable is false.
To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false. Boolean values are not actually stored in Boolean variables as the words “true” or “false”. Instead, they are stored as integers: true becomes the integer 1, and false becomes the integer 0.
The value of the bool will is undefined. It will be whatever else was on the stack before it, which is sometimes zeroed out if nothing has used it previously. But again, it is undefined, which means it can be either true or false.
The default value of the bool type is false .
The default value of Boolean is False .
You're almost certainly better off just using myFlag = true;
.
About the best you can hope for from the if (!myFlag) myFlag = true;
is that the compiler will notice that the if
is irrelevant and optimize it away. In particular, the if
statement needs to read the current value of myFlag
. If the value isn't already in the cache, that means the instruction will stall while waiting for the data to be read from memory.
By contrast, if you just write (without testing first) the value can be written to a write queue, and then more instructions can execute immediately. You won't get a stall until/unless you read the value of myFlag (and assuming it's read reasonably soon after writing, it'll probably still be in the cache, so stalling will be minimal).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With