最近在研究IL,发现一个奇怪的现象,代码说明如下:
方法一:
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
static void TestString(string s)
{
Console.WriteLine(s);
}
方法二:
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
static void TestString2(string s)
{
string str = s;
Console.WriteLine(str);
}
方法一的IL:
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
.method private hidebysig static void TestString(string s) cil managed
{
// Code size 9 (0x9)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call void [mscorlib]System.Console::WriteLine(string)
IL_0007: nop
IL_0008: ret
} // end of method Program::TestString
方法二的IL:
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
.method private hidebysig static void TestString2(string s) cil managed
{
// Code size 11 (0xb)
.maxstack 1
.locals init ([0] string str)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: call void [mscorlib]System.Console::WriteLine(string)
IL_0009: nop
IL_000a: ret
} // end of method Program::TestString2
方法一的最大栈是8,方法二的最大栈是1,很明显, 方法二的IL行数比方法一多,且两个方法基本执行了相同的命令,按理说方法二的CLR编译并执行的时间更长,但最大栈数却比方法一少。这难道是IL的以时间换空间思想?
注:经测试,两个方法的实际执行时间基本相同。