Is there a performance difference between the following two pieces of code?
if (myCondition)
{
return "returnVal1";
}
return "returnVal2"
and
if (myCondition)
{
return "returnVal1";
}
else
{
return "returnVal2";
}
My gut feeling is that the compiler should optimize for this and there shouldn’t be a difference, but I frequently see it done both ways throughout our code. I’d like to know if it comes down to a matter of preference and readability.
The best way to find out is to look at the code! Here’s the code the VS2005 C# produced in release mode:
Which shows the two version produce the exact same code, as you would hope for. I also tried a third option:
which is far more efficient as it never branches (and branches are usually bad!).
EDIT
Actually, the best way to find out which is more efficient is to profile the code, not look at the assembler.
Also, the code it’s produced is quite unusual. The push eax / mov [],ecx bit is the same, surely, as a single push ecx. Also, it passes by register then stores the value on the stack. I wonder if running the code in the debugger to look at the assembler is changing the way the code is generated.