Reputation: 397
I have the following line in a function to count the number of 'G' and 'C' in a sequence:
count += (seq[i] == 'G' || seq[i] == 'C');
Are compilers smart enough to do nothing when they see 'count += 0' or do they actually lose time 'adding' 0 ?
Upvotes: 3
Views: 470
Reputation: 477000
Honestly, who cares??
[Edit:] This actually turned out somewhat interesting. Contrary to my initial assumption, in unoptimized compilation, n += b;
is better than n += b ? 1 : 0;
. However, with optimizations, the two are identical. More importantly, though, the optimized version of this form is always better than if (b) ++n;
, which always creates a cmp/je
instruction. [/Edit]
If you're terribly curious, put the following code through your compiler and compare the resulting assembly! (Be sure to test various optimization settings.)
int n;
void f(bool b) { n += b ? 1 : 0; }
void g(bool b) { if (b) ++n; }
I tested it with GCC 4.6.1: With g++
and with no optimization, g()
is shorter. With -O3
, however, f()
is shorter:
g(): f():
cmpb $0, 4(%esp) movzbl 4(%esp), %eax
je .L1 addl %eax, n
addl $1, n
.L1:
rep
Note that the optimization for f()
actually does what you wrote originally: It literally adds the value of the conditional to n
. This is in C++ of course. It'd be interesting to see what the C compiler would do, absent a bool
type.
Another note, since you tagged this C as well: In C, if you don't use bools (from <stdbool.h>
) but rather int
s, then the advantage of one version over the other disappears, since both now have to do some sort of testing.
Upvotes: 4
Reputation: 23135
Generally
x += y;
is faster than
if (y != 0) { x += y; }
Even if y = 0
, because there is no branch in the first option. If its really important, you'll have to check the compiler output, but don't assume your way is faster because it sometimes doesn't do an add.
Upvotes: 7
Reputation: 5421
Compilers will NOT optimize away the +0 unless the expression on the right is a compiler const value equaling zero. But adding zero is much faster on all modern processors than branching (if then) to attempt to avoid the add. So the compiler ends up doing the smartest thing available in the given situation- simply adding 0.
Upvotes: 2
Reputation: 31579
Some are and some are not smart enough. its highly dependent on the optimizer implementation.
The optimizer might also determine that if
is slower than +
so it will still do the addition.
Upvotes: 1
Reputation: 62048
It depends on your compiler, its optimization options that you used and its optimization heuristics. Also, on some architectures it may be faster to add than to perform a conditional jump to avoid the addition of 0.
Upvotes: 2