当您将代码包装在 try/catch 块中时,编译器会发出更多 IL;看,对于以下程序:
using System;
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("abc");
}
}
编译器会发出这个 IL:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 13 (0xd)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "abc"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
} // end of method Program::Main
而对于稍作修改的版本:
using System;
public class Program
{
static void Main(string[] args)
{
try { Console.WriteLine("abc"); }
catch { }
}
}
发出更多:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 23 (0x17)
.maxstack 1
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: ldstr "abc"
IL_0007: call void [mscorlib]System.Console::WriteLine(string)
IL_000c: nop
IL_000d: nop
IL_000e: leave.s IL_0015
} // end .try
catch [mscorlib]System.Object
{
IL_0010: pop
IL_0011: nop
IL_0012: nop
IL_0013: leave.s IL_0015
} // end handler
IL_0015: nop
IL_0016: ret
} // end of method Program::Main
所有这些 NOP 和其他成本。