《.net 框架程序设计》里的几句代码,我重新整理了一下,写成函数,这样下面的反编译代码看起来更方便点:
public void Boxing()
{
Int32 v = 5;
Console.WriteLine("{0},{1},{2}",v,v,v);
}
public void Boxing1()
{
Int32 v = 5;
object o = v;
Console.WriteLine("{0},{1},{2}",o,o,o);
}两个函数的输出结果是一样的,但是哪一个函数更好呢?
第一个显然更简单,但是在性能上第二个好,看看反编译的代码:
Boxing函数:
.method public hidebysig instance void Boxing() cil managed
{
// Code Size: 31 byte(s)
.maxstack 4
.locals (
int32 V_0)
L_0000: ldc.i4.5
L_0001: stloc.0
L_0002: ldstr "{0},{1},{2}"
L_0007: ldloc.0
L_0008: box int32
L_000d: ldloc.0
L_000e: box int32
L_0013: ldloc.0
L_0014: box int32
L_0019: call void [mscorlib]System.Console::WriteLine(string, object, object, object)
L_001e: ret
}
Boxing1函数的:
.method public hidebysig instance void Boxing1() cil managed
{
// Code Size: 23 byte(s)
.maxstack 4
.locals (
int32 V_0,
object V_1)
L_0000: ldc.i4.5
L_0001: stloc.0
L_0002: ldloc.0
L_0003: box int32
L_0008: stloc.1
L_0009: ldstr "{0},{1},{2}"
L_000e: ldloc.1
L_000f: ldloc.1
L_0010: ldloc.1
L_0011: call void [mscorlib]System.Console::WriteLine(string, object, object, object)
L_0016: ret
}
第一个函数有三次装箱操作,第二个只有一次,在内存和时间消耗上都要小些。