The fastest way to determine value based on boolean C ++

If you have boolean b and int i , which of the two examples is better?

 int x = i-1; if(!b)x--; 

or

 int x; if(b)x = i-1;else x = i-2; 

In both examples, if b true x is i-1 , else x is i-2 . Should you declare x as i-1 and decrease if b is false or should the second example be used?

+6
source share
2 answers

I would be surprised if the compilers did not optimize both versions to the same optimal build. Do not waste time on this micro-optimization if you cannot prove that they are important using the profiler.

To answer your question: it does not matter. This compares the "generated assembly" on gcc.godbolt.org with -Ofast .


 volatile int state0; volatile void f0(volatile int i, volatile bool b) { int x; if(b)x = i-1;else x = i-2; state0 = x; } 

... compiled for ...

 f0(int, bool): # @f0(int, bool) mov dword ptr [rsp - 4], edi mov byte ptr [rsp - 5], sil movzx eax, byte ptr [rsp - 5] or eax, -2 add eax, dword ptr [rsp - 4] mov dword ptr [rip + state0], eax ret 

 volatile int state1; volatile void f1(volatile int i, volatile bool b) { int x = i-1; if(!b)x--; state1 = x; } 

... compiled for ...

 f1(int, bool): # @f1(int, bool) mov dword ptr [rsp - 4], edi mov byte ptr [rsp - 5], sil mov eax, dword ptr [rsp - 4] movzx ecx, byte ptr [rsp - 5] or ecx, -2 add ecx, eax mov dword ptr [rip + state1], ecx ret 

As you can see, the difference is minimal and most likely will disappear when the compiler is allowed to optimize more aggressively by removing volatile .


Here's a similar comparison in image form using -Ofast -march=native -ffast-math :

Beatboat comparison

+10
source

Check the build code, as the optimizer will probably optimize both solutions for the same solution.

I would probably use it like:

 int x = (b) ? i - 1 : i - 2; 

For readability and high probability, the optimizer will make it equal to your second solution.

+5
source

Source: https://habr.com/ru/post/1013916/


All Articles