让我们比较两段代码:
String str = null;
//Possibly do something...
str = "Test";
Console.WriteLine(str);
Run Code Online (Sandbox Code Playgroud)
和
String str;
//Possibly do something...
str = "Test";
Console.WriteLine(str);
Run Code Online (Sandbox Code Playgroud)
我一直认为这些代码是相同的.但是在我构建这些代码(检查了优化的发布模式)并比较生成的IL方法后,我注意到第一个样本中还有两个IL指令:
第一个示例代码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 (字符串)
IL_000e:ret
第二个示例代码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
可能这个代码是由JIT compiller优化的?那么带有null的本地bethod变量的初始化会影响性能(我知道这是非常简单的操作,但无论如何)我们应该避免它吗?先谢谢.