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?
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.
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.
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.
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.
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