Because I enjoy IL so much, I thought I'd do a small test to see what the differences were, if any, in the IL of a given chunk of code. In this case, I was interested to see how the compilers generated IL based on how Return statements are structured. For example, look at these two methods in VB:
Public Function CheckX1(ByVal x As Integer) As Boolean
If (x < 0) Then
Return False
Else
Return True
End If
End Function
Public Function CheckX2(ByVal x As Integer) As Boolean
If (x < 0) Then
Return False
End If
Return True
End Function
Both methods do exactly the same thing and will produce exactly the same result, yet are written in a slightly different way. In my pre-.NET years, I wrote code like the first method and when I got into .NET, I started writing code like the second one. I'm not really sure why I changed my style, other than it just seems “cleaner“ to me now than it did when I was a wee lad.
So given these two methods, you'd expect the IL to be pretty damn close, if not the same (hoping for some compiler opimization). In VB, the IL is almost the same, with the first method containin 19 IL instructions and the second one containing 16 instructions. We don't get any optimization from the VB compiler on this, which is OK because we're talking nanoseconds here, but still, it would be nice to have.
Now let's take this example and turn it into C#, with the code as follows:
public
bool CheckX1(int x)
{
if (x < 0)
{
return false;
}
else
{
return true;
}
}
public
bool CheckX2(int x)
{
if (x < 0)
{
return false;
}
return true;
}
If you take this C# code, compile it, and look at the IL, you'd see that the IL for both methods is *exactly the same*. You'd also see that the number of IL instructions is 14, which is less than either one of the above VB methods. Unlike the VB compiler above, the C# compiler is doing some optimization for us which results is an ever-so-slight-hardly-even-noticeable performance gain.
So the purpose of this post was two-fold: 1) to show you that structuring your Return statements as found in the CheckX2 methods above results in slightly faster code and 2) don't always believe Microsoft when they tell you that all C# and VB code gets compiled down to the same IL.
Print | posted on Saturday, May 28, 2005 11:29 PM