Lets compare two pieces of code:
String str = null;
//Possibly do something...
str = "Test";
Console.WriteLine(str);
and
String str;
//Possibly do something...
str = "Test";
Console.WriteLine(str);
I was always thinking that these pieces of code are equal. But after I have build these code (Release mode with optimization checked) and compared IL methods generated I have noticed that there are two more IL instructions in the first sample:
1st sample code IL:
.maxstack 1
.locals init ([0] string str)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldstr "Test"
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: call void [mscorlib]System.Console::WriteLine(string)
IL_000e: ret
2nd sample code IL:
.maxstack 1
.locals init ([0] string str)
IL_0000: ldstr "Test"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: call void [mscorlib]System.Console::WriteLine(string)
IL_000c: ret
Possibly this code is optimized by JIT compiller? So does the initialization of local bethod variable with null impacts the performence (I understand that it is very simple operation but any case) and we should avoid it? Thanks beforehand.
There is absolutely no reason why variables shouldn't be initialised, the compiler is clever enough to ignore the first assignment if a variable is being assigned twice. It is easy for code to grow in size where things you took for granted (such as assigning a variable before being used) are no longer true.
Initializing a variable as Telastyn pointed out can prevent bugs. If the variable is a reference type, initializing it can prevent null reference errors down the line. A variable of any type that has a non null default will take up some memory to store the default value.
The code must initialize local variables before usage. This code causes a compilation error. Initialize the variable a to its default value of null or default to fix this issue. Local variables have a maximum scope of the method that contains them.
Java designers believe every variable should be properly initialized. To initialize a variable is to give it a correct initial value. It's so important to do this that Java either initializes a variable for you, or it indicates an error has occurred, telling you to initialize a variable.
http://www.codinghorror.com/blog/2005/07/for-best-results-dont-initialize-variables.html
To summarize from the article, after running various benchmarks, initializing an object to a value (either as part of a definition, in the class' constructor, or as part of an initialization method) can be anywhere from roughly 10-35% slower on .NET 1.1 and 2.0. Newer compilers may optimize away initialization on definition. The article closes by recommending to avoid initialization as a general rule.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With