Reputation:
If you have a boolean b
and an int i
, which one 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
is true x
is i-1
, else x
is i-2
. Should you declare x
as i-1
and decrement if b
is false or should you use the second example?
Upvotes: 6
Views: 303
Reputation: 93264
I would be surprised if compilers didn't optimize both version to the same optimal assembly. Don't waste your time with this micro-optimizations unless you can prove that they are significant using a profiler.
To answer your question: it's irrelevant. Here's a "generated assembly" comparison 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;
}
...gets compiled to...
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;
}
...gets compiled to...
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 is extremely likely to disappear when the compiler is allowed to optimize more aggressively by removing volatile
.
Here's a similar comparison in picture form, using -Ofast -march=native -ffast-math
:
Upvotes: 10
Reputation: 15347
Check the assembly code, since the optimizer will optimize, possibly both your solutions to the same solution.
I would probably implement it as:
int x = (b) ? i - 1 : i - 2;
For readability and high likely the optimizer will make it equal as your second solution.
Upvotes: 5