Explicit assignment slower

Mon, May 30, 2005, 09:58 AM under dotNET
As you know, in VB variables do not need to be initialised, as they always get the default value for the variable type in question, e.g.
Dim b As Boolean 'b is already initialised to False

In C-based languages (inc. C#) this does not apply; you must initialise the variable before you use it, e.g.
bool b = false;

The above is the reason we cannot have ByOut in VB (only ByVal and ByRef) whereas C# has both ref and out (ByVal is implied by omission).

I have seen VB code that follows the C-style and there are two common reasons for doing so; one is to be explicit and the other is because of a C-based upbringing. The question is what IL will the VB compiler generate, faced with code that differs only by explicit assignment (we know it is pretty crap at optimising the simplest of scenarios, so we don't go in with our hopes high).

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 (I have to say if you have a bottleneck in your project, cases like this will not be it, but it is still good to know :-).

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
Needless to say that the C# version closely reflects the first version (it is even better, since it uses a call rather than a callvirt - but that is a different story...).