I was creating a C# method in visual studio that contained only a switch statement where each case returned a value. By personal habit, I put something similar to the following code:
private string SwitchMethod(int num)
{
switch (num)
{
case 0:
return "result 1";
case 1:
return "result 2";
case 2:
return "result 3";
}
return "no result";
}
My question is this: Which code will have better performance? The code above or below, or are the same? And why?
I would assume that because of compiler optimizations…they might just be the same…but I really don’t know.
private string SwitchMethod(int num)
{
switch (num)
{
case 0:
return "result 1";
case 1:
return "result 2";
case 2:
return "result 3";
default:
return "no result";
}
}
REVISION:
It seems that I should be more specific: When compiled…will less efficient code be generated by one or the other?
I realize that the difference in performance may be insignificant…I’m just curious really.
Becomes:
Moving the return into a default case:
Exactly the same. No performance difference. I changed the “no result” to result 4 just to make sure the code was regenerated. Apparently the C# compiler optimizes it or it just ends up being equivalent.