开发者

C/C++: adding 0

开发者 https://www.devze.com 2023-04-11 21:56 出处:网络
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\');

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 th开发者_如何学运维ey see 'count += 0' or do they actually lose time 'adding' 0 ?


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.


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 ints, then the advantage of one version over the other disappears, since both now have to do some sort of testing.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消