I am currently trying to improve the speed of my program.
I was wondering whether it would help to replace all if-statements of the type:
bool a=1;
int b=0;
if(a){b++;}
with this:
bool a=1;
int b=0;
b+=a;
I am unsure whether the conversion from bool to int could be a problem time-wise.
Compilers are allowed to assume that the underlying value of a
bool
isn't messed up, so optimizing compilers can avoid the branch.If we look at the generated code for this artificial test
clang will exploit this fact and generate the exact same branchless code that sums
a
andb
for thebool
version, and instead generate actual comparisons with zero in theunsigned char
case (although it's still branchless code):gcc will instead treat
bool
just as if it was anunsigned char
, without exploiting its properties, generating similar code as clang'sunsigned char
case.Finally, Visual C++ will treat the
bool
and theunsigned char
versions equally, just as gcc, although with more naive codegen (it uses a conditional move instead of performing arithmetic with the flags register, which IIRC traditionally used to be less efficient, don't know for current machines).In all cases, no branches are generated; the only difference is that, on most compilers, some more complex code is generated that depends on a
cmp
or atest
, creating a longer dependency chain.That being said, I would worry about this kind of micro-optimization only if you actually run your code under a profiler, and the results point to this specific code (or to some tight loop that involve it); in general you should write sensible, semantically correct code and focus on using the correct algorithms/data structures. Micro-optimization comes later.
This should be even better for the optimizer, as it doesn't even have any doubt about where the
bool
is coming from - it can just decide straight from the flags register. As you can see, here gcc produces quite similar code for the two cases, clang exactly the same, while VC++ as usual produces something that is more conditional-ish (acmov
) in theif
case.