Reputation: 288120
If I have a boolean and some code which maybe changes it, and then I want to set it to true
, should I check if it's false
?
For example:
bool b = false;
// Some code
// Here "b" can be true or false
if (cond) {
b = true;
}
vs
bool b = false;
// Some code
// Here `b` can be `true` or `false`
if (cond && !b){
b = true;
}
Which is faster?
Note:
I ask that because of the following implementation of Sieve of Eratosthenes: http://bloc.gerardfarras.com/wp-content/uploads/2011/12/erastotenes.txt
if (( i % divisor == 0 ) && ( numsprimers[i] == 0 )) {
numsprimers[i] = 1;
}
(If numsprimers[i]==1
it means that i
isn't a prime number. And if it's 0 it can be prime or not)
Upvotes: 11
Views: 3183
Reputation: 96810
How about:
if ( b = !!cond ) {
}
Where you check the condition and apply the value to b
, if it is necessary for b
to have a value. If you want b
to stay true then I say to use one of your other examples. It shouldn't make a difference.
Upvotes: 0
Reputation: 2917
It's being very very nitpicky, but generally speaking it's better to just change the value.
Checking and setting a value have roughly the same overhead anyway, so why would you want to have to do both in some cases?
Now if you're wondering if you should overwrite some custom type (lets say a list of 100000 words) or if you should check to see if it needs to be overwritten first (let's say by simply checking a boolean value or a timestamp) then you should check first, because the cost of checking a boolean or timestamp is much less than writing so many words to memory.
This is of course all dependent on various things such as whether or not the memory you are editing is in cache, how expensive the "check" is, how often you need to overwrite the value versus how often it does not need to be overwritten, and of course the size of the memory.
Upvotes: 6