如果使用反射来检查这个生成的代码:
public MemoryStream GetStream(byte[] bytes)
{
MemoryStream s = new MemoryStream(bytes);
return s;
}
对于发布版本,你会得到:
.method public hidebysig instance class [mscorlib]System.IO.MemoryStream GetStream(uint8[] bytes) cil managed
{
.maxstack 1
.locals init (
[0] class [mscorlib]System.IO.MemoryStream s)
L_0000: ldarg.1
L_0001: newobj instance void [mscorlib]System.IO.MemoryStream::.ctor(uint8[])
L_0006: stloc.0
L_0007: ldloc.0
L_0008: ret
}
因此,大家可以看到,C#编译器优化掉了额外的变量。
然而,对于调试版本,你会得到:
.method public hidebysig instance class [mscorlib]System.IO.MemoryStream GetStream(uint8[] bytes) cil managed
{
.maxstack 1
.locals init (
[0] class [mscorlib]System.IO.MemoryStream s,
[1] class [mscorlib]System.IO.MemoryStream CS$1$0000)
L_0000: nop
L_0001: ldarg.1
L_0002: newobj instance void [mscorlib]System.IO.MemoryStream::.ctor(uint8[])
L_0007: stloc.0
L_0008: ldloc.0
L_0009: stloc.1
L_000a: br L_000f
L_000f: ldloc.1
L_0010: ret
}
显然编译器不能优化掉的调试版本额外的变量,如果你要检查它在调试。
因此,如果您想为调试目的而保留额外的变量,那么它很好 - 它对发布版本没有任何影响。
我想,这是个人喜好。我看不出可以对此代码进行哪些优化。 – shahkalpesh
无论如何编译器会内联整个方法。 –