Не будет разницы в производительности.using
расширяется компилятором до блока try / finally.
Вы увидите, что следующие два метода компилируются для идентичного IL.
void SampleWithUsing()
{
using (MemoryStream s = new MemoryStream())
{
s.WriteByte(1);
}
}
void SampleWithTryFinally()
{
MemoryStream s = new MemoryStream();
try
{
s.WriteByte(1);
}
finally
{
if (s != null) s.Dispose();
}
}
IL, сгенерированный в первом случае:
.method private hidebysig instance void SampleWithUsing() cil managed
{
// Code size 26 (0x1a)
.maxstack 2
.locals init ([0] class [mscorlib]System.IO.MemoryStream s)
IL_0000: newobj instance void [mscorlib]System.IO.MemoryStream::.ctor()
IL_0005: stloc.0
.try
{
IL_0006: ldloc.0
IL_0007: ldc.i4.1
IL_0008: callvirt instance void [mscorlib]System.IO.Stream::WriteByte(uint8)
IL_000d: leave.s IL_0019
} // end .try
finally
{
IL_000f: ldloc.0
IL_0010: brfalse.s IL_0018
IL_0012: ldloc.0
IL_0013: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_0018: endfinally
} // end handler
IL_0019: ret
} // end of method Program::SampleWithUsing
Во втором случаепри попытке / наконец в C # мы получаем:
.method private hidebysig instance void SampleWithTryFinally() cil managed
{
// Code size 26 (0x1a)
.maxstack 2
.locals init ([0] class [mscorlib]System.IO.MemoryStream s)
IL_0000: newobj instance void [mscorlib]System.IO.MemoryStream::.ctor()
IL_0005: stloc.0
.try
{
IL_0006: ldloc.0
IL_0007: ldc.i4.1
IL_0008: callvirt instance void [mscorlib]System.IO.Stream::WriteByte(uint8)
IL_000d: leave.s IL_0019
} // end .try
finally
{
IL_000f: ldloc.0
IL_0010: brfalse.s IL_0018
IL_0012: ldloc.0
IL_0013: callvirt instance void [mscorlib]System.IO.Stream::Dispose()
IL_0018: endfinally
} // end handler
IL_0019: ret
} // end of method Program::SampleWithTryFinally