C#编译器对局部变量的优化指南
前言
C#的编译器可以对代码进行优化,所以,我们在写代码的时候,可以更多地考虑一下代码的易读性问题。
不考虑基本的对齐和换行美化。看一下局部变量优化问题。
C#示例代码
例如,我们有一段如下的代码:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceConsoleApp1
{
classProgram
{
staticvoidMain(string[]args)
{
vars=DoSomething();
Console.WriteLine(s);
}
staticstringDoSomething()
{
vars1="Hello,world.";
vars2=s1.ToUpper();
returns2;
}
}
}
在DoSomething()这个方法中,里面定义了两个局部变量:
- s1
- s2
在Main()方法中,定义了一个局部变量:
- s
定义s1和s2是为了提高代码的可读性,它们会导致生成冗余的代码,降低执行效率吗?
我们分别在Debug模式下和Release模式下进行编译,使用ILDasm查看生成的中间代码。
Debug模式下生成的中间代码
在Debug下编译之后,DoSomething()生成的中间代码如下,可以看到实际上有3个局部变量。除了我们自己定义的s1和s2之外,还有一个生成的V_2,代码的尺寸为20。
.methodprivatehidebysigstaticstringDoSomething()cilmanaged
{
//Codesize20(0x14)
.maxstack1
.localsinit([0]strings1,
[1]strings2,
[2]stringV_2)
IL_0000:nop
IL_0001:ldstr"Hello,world."
IL_0006:stloc.0
IL_0007:ldloc.0
IL_0008:callvirtinstancestring[mscorlib]System.String::ToUpper()
IL_000d:stloc.1
IL_000e:ldloc.1
IL_000f:stloc.2
IL_0010:br.sIL_0012
IL_0012:ldloc.2
IL_0013:ret
}//endofmethodProgram::DoSomething
看一下Main()方法。
有我们定义的s这一个局部变量,代码尺寸为15个字节。
.methodprivatehidebysigstaticvoidMain(string[]args)cilmanaged
{
.entrypoint
//Codesize15(0xf)
.maxstack1
.localsinit([0]strings)
IL_0000:nop
IL_0001:callstringConsoleApp1.Program::DoSomething()
IL_0006:stloc.0
IL_0007:ldloc.0
IL_0008:callvoid[mscorlib]System.Console::WriteLine(string)
IL_000d:nop
IL_000e:ret
}//endofmethodProgram::Main
Release模式下生成的中间代码
而在Release模式下,实际上,DoSomething()中所有的局部变量都被优化掉了。代码尺寸也只有11个字节。
.methodprivatehidebysigstaticstringDoSomething()cilmanaged
{
//Codesize11(0xb)
.maxstack8
IL_0000:ldstr"Hello,world."
IL_0005:callvirtinstancestring[mscorlib]System.String::ToUpper()
IL_000a:ret
}//endofmethodProgram::DoSomething
还可以看一下Main()方法,这个局部变量s也被优化掉了。代码尺寸也只有11字节了。
.methodprivatehidebysigstaticvoidMain(string[]args)cilmanaged
{
.entrypoint
//Codesize11(0xb)
.maxstack8
IL_0000:callstringConsoleApp1.Program::DoSomething()
IL_0005:callvoid[mscorlib]System.Console::WriteLine(string)
IL_000a:ret
}//endofmethodProgram::Main
结论
编译器会尽可能对代码进行优化,我们可以为了提高代码的易读性增加一些局部变量,这并不会导致生成冗余代码并导致执行性能的下降。
到此这篇关于C#编译器对局部变量优化的文章就介绍到这了,更多相关C#编译器对局部变量优化内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!