The performance of catch(...) vs. catch vs. finally constructs came up in conversation today at work. Consider the following sample code:
using System;
namespace SoftwareIsHardwork
{
public class Program
{
public static void Main()
{
}
public void MethodA()
{
try
{
}
catch (Exception ex)
{
}
}
public void MethodB()
{
try
{
}
catch
{
}
}
public void MethodC()
{
try
{
}
finally
{
}
}
}
}
The methods MethodA, MethodB, and MethodC yield the following MSIL when compiled in debug mode*:
.method public hidebysig instance void MethodA() cil managed
{
// Code size 12 (0xc)
.maxstack 1
.locals init (class [mscorlib]System.Exception V_0)
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: nop
IL_0003: leave.s IL_000a
} // end .try
catch [mscorlib]System.Exception
{
IL_0005: stloc.0
IL_0006: nop
IL_0007: nop
IL_0008: leave.s IL_000a
} // end handler
IL_000a: nop
IL_000b: ret
} // end of method Program::MethodA
.method public hidebysig instance void MethodB() cil managed
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: nop
IL_0003: leave.s IL_000a
} // end .try
catch [mscorlib]System.Object
{
IL_0005: pop
IL_0006: nop
IL_0007: nop
IL_0008: leave.s IL_000a
} // end handler
IL_000a: nop
IL_000b: ret
} // end of method Program::MethodB
.method public hidebysig instance void MethodC() cil managed
{
// Code size 10 (0xa)
.maxstack 0
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: nop
IL_0003: leave.s IL_0008
} // end .try
finally
{
IL_0005: nop
IL_0006: nop
IL_0007: endfinally
} // end handler
IL_0008: nop
IL_0009: ret
} // end of method Program::MethodC
The final analysis: finally is better than empty catch blocks...in debug mode.
* By the way, the compiler yields the following in release mode:
.method public hidebysig instance void Method() cil managed
{
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
} // end of method Program::Method
Optimized!
0 comments:
Post a Comment