EDIT: After removing the UB (good spot, I missed it), the times are more or less identical. Will flag a moderator to delete it.
These two functions are identical except for the fact that foo
has the return inside the if
, on both branches, whereas goo
has a single return
at the end:
int foo()
{
static int x = 0;
if ( x )
{
x > 2 ? x = 0 : ++x;
return x-1;
}
else
{
x++;
return x-1;
}
}
int goo()
{
static int x = 0;
if ( x )
{
x > 2 ? x = 0 : ++x;
}
else
{
x++;
}
return x-1;
}
The numbers are there just so optimizations don't kick in too hard and the function call isn't optimized away. Compiled with full optimization on MSVS 2010.
Calling the function 4000000000 times, sampled 10 times, foo
was always faster:
foo
- 8830 ms averagegoo
- 8703 ms averageThe difference is small, but it's there. Why? Also, why doesn't the compiler optimize them to the same thing?
Have a look at the assembler output, there might be a jump to the end of the function in the first branch of goo().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With