如果使用反射來檢查這個生成的代碼:
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
無論如何編譯器會內聯整個方法。 –