c# - if else vs if return single



Does it matter performance wise if there is an `else` after the first `return`? (4)

No.

Even when we look at their IL code, they have the same IL code, so there is no performance difference between them. Use the one which is more readable for you.

.method private hidebysig instance bool  Case1() cil managed
{
  // Code size       9 (0x9)
  .maxstack  1
  .locals init ([0] bool CS$1$0000,
           [1] bool CS$4$0001)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.1
  IL_0003:  ldc.i4.1
  IL_0004:  stloc.0
  IL_0005:  br.s       IL_0007
  IL_0007:  ldloc.0
  IL_0008:  ret
} // end of method Program::Case1

Look at these pieces of code for their performances;

http://ideone.com/8Sc7Ho --> Memory: 33856 kB

http://ideone.com/MrnaAl --> Memory: 33808 kB

So if you use them even 10.000 times, there is nothing to worry about.

https://src-bin.com

I've now seen two different ways to make a boolean returning method:

bool Case1()
{
    if (A)
        return true;
    else
        return false;
}
bool Case2()
{
    if (A)
        return true;
    return false;
}

Which one is faster? Does it make sense to not write else just to save a line, make it clearer, or is there a negligible performance gain?


Answer #1

Performance wise they are the same. From a good coding practices standpoint, prefer the latter - so that it is clear the function always returns a valid value.


Answer #2

There is going to be no(negligible) difference. From a coding standpoint you really should just do:

return A;

But assuming the code was just for an example then I would suggest:

bool Case3()
{
    bool retValue;
    if (A)
    {
        retValue = true;
    } 
    else
    { 
        retValue = false;
    }
    return retValue;
}

This way you are very clear about what is happening, and what value is to be returned. If you need to go back and change the functionality of what the method does, it is much easier.


Answer #3

They are the same.

If A is false there will be a jump to the return false statement in both cases.





return