欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

再议C#中的装箱与拆箱的问题详解

程序员文章站 2023-12-20 15:08:58
上一篇写了一下装箱拆箱的定义和il分析,这一篇我们看下使用泛型和不使用泛型引发装箱拆箱的情况1.使用非泛型集合时引发的装箱和拆箱操作 看下面的一段代码:复制代码 代码如下:...
上一篇写了一下装箱拆箱的定义和il分析,这一篇我们看下使用泛型和不使用泛型引发装箱拆箱的情况
1.使用非泛型集合时引发的装箱和拆箱操作
看下面的一段代码:
复制代码 代码如下:

var array = new arraylist();
array.add(1);
array.add(2);

foreach (int value in array)
{
console.writeline(“value is {0}”,value);
}

代码声明了一个arraylist对象,向arraylist中添加两个数字1,2;然后使用foreach将arraylist中的元素打印到控制台。
在这个过程中会发生两次装箱操作和两次拆箱操作,在向arraylist中添加int类型元素时会发生装箱,在使用foreach枚举arraylist中的int类型元素时会发生拆箱操作,将object类型转换成int类型,在执行到console.writeline时,还会执行两次的装箱操作;这一段代码执行了6次的装箱和拆箱操作;如果arraylist的元素个数很多,执行装箱拆箱的操作会更多。
你可以通过使用ilspy之类的工具查看il代码的box,unbox指令查看装箱和拆箱的过程
2.使用泛型集合的情况
请看如下代码:
复制代码 代码如下:

var list = new list<int>();
list.add(1);
list.add(2);

foreach (int value in list)
{
console.writeline("value is {0}", value);
}

代码和1中的代码的差别在于集合的类型使用了泛型的list,而非arraylist;我们同样可以通过查看il代码查看装箱拆箱的情况,上述代码只会在console.writeline()方法时执行2次装箱操作,不需要拆箱操作。
可以看出泛型可以避免装箱拆箱带来的不必要的性能消耗;当然泛型的好处不止于此,泛型还可以增加程序的可读性,使程序更容易被复用等等。
本文使用的c#代码如下:
复制代码 代码如下:

using system;
using system.collections;
using system.collections.generic;

namespace boxorunbox
{
    class program
    {
        static void main(string[] args)
        {
            //do nothing
        }

        static void box()
        {
            object objvalue = 9;
        }

        static void unbox()
        {
            object objvalue = 4;
            int value = (int)objvalue;
        }

        static void lookatarraylist()
        {
            var array = new arraylist();
            array.add(1);
            array.add(2);

            foreach (int value in array)
            {
                console.writeline("value is {0}", value);
            }
        }

        static void lookatgenericlist()
        {
            var list = new list<int>();
            list.add(1);
            list.add(2);

            foreach (int value in list)
            {
                console.writeline("value is {0}", value);
            }
        }
    }
}

c#的il代码如下:
复制代码 代码如下:

.class private auto ansi beforefieldinit boxorunbox.program
    extends [mscorlib]system.object
{
    // methods
    .method private hidebysig static
        void main (
            string[] args
        ) cil managed
    {
        // method begins at rva 0x2050
        // code size 2 (0x2)
        .maxstack 8
        .entrypoint

        il_0000: nop
        il_0001: ret
    } // end of method program::main

    .method private hidebysig static
        void box () cil managed
    {
        // method begins at rva 0x2054
        // code size 10 (0xa)
        .maxstack 1
        .locals init (
            [0] object objvalue
        )

        il_0000: nop
        il_0001: ldc.i4.s 9
        il_0003: box [mscorlib]system.int32
        il_0008: stloc.0
        il_0009: ret
    } // end of method program::box

    .method private hidebysig static
        void unbox () cil managed
    {
        // method begins at rva 0x206c
        // code size 16 (0x10)
        .maxstack 1
        .locals init (
            [0] object objvalue,
            [1] int32 'value'
        )

        il_0000: nop
        il_0001: ldc.i4.4
        il_0002: box [mscorlib]system.int32
        il_0007: stloc.0
        il_0008: ldloc.0
        il_0009: unbox.any [mscorlib]system.int32
        il_000e: stloc.1
        il_000f: ret
    } // end of method program::unbox

    .method private hidebysig static
        void lookatarraylist () cil managed
    {
        // method begins at rva 0x2088
        // code size 114 (0x72)
        .maxstack 2
        .locals init (
            [0] class [mscorlib]system.collections.arraylist 'array',
            [1] int32 'value',
            [2] class [mscorlib]system.collections.ienumerator cs$5$0000,
            [3] bool cs$4$0001,
            [4] class [mscorlib]system.idisposable cs$0$0002
        )

        il_0000: nop
        il_0001: newobj instance void [mscorlib]system.collections.arraylist::.ctor()
        il_0006: stloc.0
        il_0007: ldloc.0
        il_0008: ldc.i4.1
        il_0009: box [mscorlib]system.int32
        il_000e: callvirt instance int32 [mscorlib]system.collections.arraylist::add(object)
        il_0013: pop
        il_0014: ldloc.0
        il_0015: ldc.i4.2
        il_0016: box [mscorlib]system.int32
        il_001b: callvirt instance int32 [mscorlib]system.collections.arraylist::add(object)
        il_0020: pop
        il_0021: nop
        il_0022: ldloc.0
        il_0023: callvirt instance class [mscorlib]system.collections.ienumerator [mscorlib]system.collections.arraylist::getenumerator()
        il_0028: stloc.2
        .try
        {
            il_0029: br.s il_004a
            // loop start (head: il_004a)
                il_002b: ldloc.2
                il_002c: callvirt instance object [mscorlib]system.collections.ienumerator::get_current()
                il_0031: unbox.any [mscorlib]system.int32
                il_0036: stloc.1
                il_0037: nop
                il_0038: ldstr "value is {0}"
                il_003d: ldloc.1
                il_003e: box [mscorlib]system.int32
                il_0043: call void [mscorlib]system.console::writeline(string, object)
                il_0048: nop
                il_0049: nop

                il_004a: ldloc.2
                il_004b: callvirt instance bool [mscorlib]system.collections.ienumerator::movenext()
                il_0050: stloc.3
                il_0051: ldloc.3
                il_0052: brtrue.s il_002b
            // end loop

            il_0054: leave.s il_0070
        } // end .try
        finally
        {
            il_0056: ldloc.2
            il_0057: isinst [mscorlib]system.idisposable
            il_005c: stloc.s cs$0$0002
            il_005e: ldloc.s cs$0$0002
            il_0060: ldnull
            il_0061: ceq
            il_0063: stloc.3
            il_0064: ldloc.3
            il_0065: brtrue.s il_006f

            il_0067: ldloc.s cs$0$0002
            il_0069: callvirt instance void [mscorlib]system.idisposable::dispose()
            il_006e: nop

            il_006f: endfinally
        } // end handler

        il_0070: nop
        il_0071: ret
    } // end of method program::lookatarraylist

    .method private hidebysig static
        void lookatgenericlist () cil managed
    {
        // method begins at rva 0x2118
        // code size 90 (0x5a)
        .maxstack 2
        .locals init (
            [0] class [mscorlib]system.collections.generic.list`1<int32> list,
            [1] int32 'value',
            [2] valuetype [mscorlib]system.collections.generic.list`1/enumerator<int32> cs$5$0000,
            [3] bool cs$4$0001
        )

        il_0000: nop
        il_0001: newobj instance void class [mscorlib]system.collections.generic.list`1<int32>::.ctor()
        il_0006: stloc.0
        il_0007: ldloc.0
        il_0008: ldc.i4.1
        il_0009: callvirt instance void class [mscorlib]system.collections.generic.list`1<int32>::add(!0)
        il_000e: nop
        il_000f: ldloc.0
        il_0010: ldc.i4.2
        il_0011: callvirt instance void class [mscorlib]system.collections.generic.list`1<int32>::add(!0)
        il_0016: nop
        il_0017: nop
        il_0018: ldloc.0
        il_0019: callvirt instance valuetype [mscorlib]system.collections.generic.list`1/enumerator<!0> class [mscorlib]system.collections.generic.list`1<int32>::getenumerator()
        il_001e: stloc.2
        .try
        {
            il_001f: br.s il_003c
            // loop start (head: il_003c)
                il_0021: ldloca.s cs$5$0000
                il_0023: call instance !0 valuetype [mscorlib]system.collections.generic.list`1/enumerator<int32>::get_current()
                il_0028: stloc.1
                il_0029: nop
                il_002a: ldstr "value is {0}"
                il_002f: ldloc.1
                il_0030: box [mscorlib]system.int32
                il_0035: call void [mscorlib]system.console::writeline(string, object)
                il_003a: nop
                il_003b: nop

                il_003c: ldloca.s cs$5$0000
                il_003e: call instance bool valuetype [mscorlib]system.collections.generic.list`1/enumerator<int32>::movenext()
                il_0043: stloc.3
                il_0044: ldloc.3
                il_0045: brtrue.s il_0021
            // end loop

            il_0047: leave.s il_0058
        } // end .try
        finally
        {
            il_0049: ldloca.s cs$5$0000
            il_004b: constrained. valuetype [mscorlib]system.collections.generic.list`1/enumerator<int32>
            il_0051: callvirt instance void [mscorlib]system.idisposable::dispose()
            il_0056: nop
            il_0057: endfinally
        } // end handler

        il_0058: nop
        il_0059: ret
    } // end of method program::lookatgenericlist

    .method public hidebysig specialname rtspecialname
        instance void .ctor () cil managed
    {
        // method begins at rva 0x2190
        // code size 7 (0x7)
        .maxstack 8

        il_0000: ldarg.0
        il_0001: call instance void [mscorlib]system.object::.ctor()
        il_0006: ret
    } // end of method program::.ctor

} // end of class boxorunbox.program

上一篇:

下一篇: