I'm sorry if it sounds like a stupid question, but: let's say that I have to change the bool variable 'a', based on a condition 'cond', but it could happens that 'a' already has the value I want to assign to it.
Now, should I do something like this:
// something that changes 'a'
if (cond) {
a = true;
}
or should I check before if the variable 'a' is already true, like this:
// something that changes 'a'
if (cond) {
if (!a) {
a = true;
}
}
Which way is faster? (and if there are differences in different programming languages)
CodePudding user response:
Use whatever is most clear to express your code's intent, which is usually the direct a = true;
. A good compiler will optimize a boolean if (!a) { a = true; }
into a = true;
so the same performance can be expected.
Avoid premature optimization.