Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 405
user1306322 Avatar asked Dec 31 '12 14:12

user1306322


People also ask

Should I use if else or return?

It depends on the semantics of your code, if the else branch is the point of the method, i.e. it's named after what happens in the else branch, the early return is probably correct, especially if the first part is some sort of check.

Should I return from a function early or use an IF statement?

One of the reasons that you could consider using early returns is that it keeps your code visually flatter. There is no need for extra indentation that you would have had if you went for the alternative route that uses a wrapping if-statement. This makes code more readable.


2 Answers

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.

like image 102
Soner Gönül Avatar answered Sep 29 '22 18:09

Soner Gönül


The c# compiler should generate the same IL for these two cases, so there should be no difference in performance. You can always view the generated IL if you are curious what actually happens (attempting to teach how to fish).

IMHO, Case1 is easier to read, which is worth something. My second choice would be return A; (as mentioned in some other answers). If A isn't a bool though, there is an implicit conversion which may be confusing in some cases.

I think readability should win unless you can prove with a profiler that you have a problem.

like image 40
WildCrustacean Avatar answered Sep 29 '22 17:09

WildCrustacean