t2.method private hidebysig static int32 Test2(int32 a,
int32 b) cil managed
{
// 代码大小 22 (0x16)
.maxstack 2
.locals init ([0] int32 CS$1$0000,
bool CS$4$0001)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: cgt
IL_0005: ldc.i4.0
IL_0006: ceq
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: brtrue.s IL_0010
IL_000c: ldarg.0
IL_000d: stloc.0
IL_000e: br.s IL_0014
IL_0010: ldarg.1
IL_0011: stloc.0
IL_0012: br.s IL_0014
IL_0014: ldloc.0
IL_0015: ret
} // end of method Program::Test2
这里我们只需关注红字高亮的几行即可。此处我们只关心try区块,即未发生异常的时候,对于Test1来讲,IL代码多出了8个字节来保存catch的处理代码,这一点对性能和资源几乎是微不足道的。
我们看到当Test1执行到IL_000f或者IL_0013的时候,将数据出栈并使用leave.s退出try区块转向IL_001b地址,然后将数据入栈并返回。
对于Test2来讲,执行到IL_000e或者IL_0012的时候, 直接退出,并将数据入栈然后返回。
这里对几个关键指令简单介绍一下
nop do noting
stloc.0 Pop value from stack into local variable 0.
ldloc.0 Load local variable 0 onto stack.
br.s target branch to target, short form
leave.s target Exit a protected region of code, short form
下面我们看代码的实际运行情况,新建一个控制台Console程序,加入下面代码:
点击左边图标展开代码
static void Main(string args)
{
int times = 1000000; //我们将结果放大100,0000倍
long l1, l2,l3,l4, s1, s2;
Console.WriteLine("Press any key to continue");
Console.Read();
for (int j = 0; j < 10; j++)
{
l1 = DateTime.Now.Ticks;
for (int i = 0; i < times; i++)
&n