VB.NET and variable initialization

This is a little performance tip that I was missing and that I want to bookmark here (thanks to Daniel Moth).

With Visual Basic .NET when you declare a variable, you have the choice to initialize it with a value or not (in this case the variable gets the default value for the variable type you're using). For example:

Dim MyVar as Boolean = False  //MyVar is initialized with the False value

Dim MyVar as Boolean  //MyVar is initialized with the default value for boolean variables, False

With C# the implicit assignment is impossible and you're forced to initialize a variable:

bool MyVar = false;

What is extremely curious to note is that with VB.NET these 2 types of variable's initialization are translated in IL code with 2 different ways. This is the Moth's example:

Given these two methods (and assuming a private method GetNumber):

    Public Sub VBStyle()
Dim i As Int32
i = GetANumber()
End Sub

Public Sub CsStyle()
Dim i As Int32 = 0
i = GetANumber()
End Sub

I can tell you that the VB compiler generates slower code for the second scenario. Here is the corresponding IL:

.method public instance void  VBStyle() cil managed
{
// Code size 8 (0x8)
.maxstack 1
.locals init ([0] int32 i)
IL_0000: ldarg.0
IL_0001: callvirt instance int32 VBWinApp.Class3::GetANumber()
IL_0006: stloc.0
IL_0007: ret
} // end of method Class3::VBStyle

.method public instance void CsStyle() cil managed
{
// Code size 10 (0xa)
.maxstack 1
.locals init ([0] int32 i)
IL_0000: ldc.i4.0
IL_0001: stloc.0

IL_0002: ldarg.0
IL_0003: callvirt instance int32 VBWinApp.Class3::GetANumber()
IL_0008: stloc.0
IL_0009: ret
} // end of method Class3::CsStyle

As you can see on the IL code, the explicit initialization generates extra IL code and it's slowest that the first initialization's method.

P.S. Obviously, we're talking here of tips for an extreme code performance optimization. On standard scenario I don't think that you can see better performances by using implicit or explicit initialization, but these tips are important to be memorized I think. If you are using VB.NET, maybe now you can decide how to declare your variables...

Print | posted on Wednesday, January 04, 2006 9:42 AM