lets say we compile the following code, under release & optimized builds
namespace ConsoleApplication4
{
public class Test1
{
private int myIntToInitalize;
public Test1()
{
myIntToInitalize = 10;
}
}
public class Test2
{
private int myIntToInitalize = 10;
}
static class Program
{
private static void Main()
{
}
}
}
The IL Instruction for Class Test1
.class public auto ansi beforefieldinit Test1
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
.maxstack 8
L_0000: ldarg.0
L_0001: call instance void [mscorlib]System.Object::.ctor()
L_0006: ldarg.0
L_0007: ldc.i4.s 10
L_0009: stfld int32 ConsoleApplication4.Test1::myIntToInitalize
L_000e: ret
}
.field private int32 myIntToInitalize
}
The IL Instruction for Class Test2
.class public auto ansi beforefieldinit Test2
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
.maxstack 8
L_0000: ldarg.0
L_0001: ldc.i4.s 10
L_0003: stfld int32 ConsoleApplication4.Test2::myIntToInitalize
L_0008: ldarg.0
L_0009: call instance void [mscorlib]System.Object::.ctor()
L_000e: ret
}
.field private int32 myIntToInitalize
}
is is very obvious that both the classes have same number of IL instruction, the only diff is,
variable is initialized before calling the ::ctor() in Class Test1;
and
variable is initialized after calling the ::ctor() in Class Test2;
NOTE : Performance wise both the Class will perform same, as they have same numbers & type of IL instruction, just that order of execution of IL Instruction is different