Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is moving return to the end of the function less efficient? [closed]

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 average
  • goo - 8703 ms average

The difference is small, but it's there. Why? Also, why doesn't the compiler optimize them to the same thing?

like image 571
Luchian Grigore Avatar asked Nov 25 '22 20:11

Luchian Grigore


1 Answers

Have a look at the assembler output, there might be a jump to the end of the function in the first branch of goo().

like image 131
Torsten Robitzki Avatar answered May 20 '23 01:05

Torsten Robitzki