(.NET) Boxing and Unboxing

本文详细解析了装箱与拆箱的概念,探讨了它们在.NET中的实现机制,包括堆内存分配、值复制和指针返回的过程。同时,文章对比了使用泛型的优势,如类型检查、强制值类型、栈分配、减少堆操作和转换,以及装箱与拆箱对应用性能的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Boxing and Unboxing

Most of us have the knowledge about "Boxing" and "Unboxing".

For "Boxing" means convert value type to reference type.

For "Unboxing" means convert reference type to value.

 

More deeper,

1. For Boxing, CLR did three things in briefly,

    (1) Allocate a heap memory.

    (2) Copy the value to heap.

    (3) Return the pointer of that "Boxed" type.

2. For Unboxing,

    (1) Unboxing.

    (2) Copy.

    Note that, I mentioned that Unboxing and Copy, because,

    (1) For Unboxing, it means that get each filed that contained the boxed type. This process is called unboxing.

    (2) For Copy, it means copy the value to the value type instance in the stack.

 

Why boxing and unboxing?

Consider ArrayList. You may want to add values to the list. But after you dig into the argument of Add method of ArrayList, you found that the parameter is "Object". So, in this case, a boxing is needed. Also, while you are reading the data, you need to convert it to value type, so a unboxing needed.

 

The disadvantage is, it will impact the performance of your application.

 

Generic

One much better way is that us "Generic Type". It has below advantages,

1. Type examine while your compiling.

2. Force to value type if you passed the value type.

3. Stack allocated while running.

4. Less operations in heap memory.

5. Less force convertion happened.

 

How many boxing are there?

Now, let's try to see an interesting code, to see how many boxing are there?

        static void Main(string[] args)
        {
            Int32 i = 5;
            object o = i;

            i = 123;
            Console.WriteLine(i + "--" + (Int32)o);
        }

A HA. One? Two? Or Three?

The answer is "three", there are three boxings happened.

 

Why it's three other 1 or 2?

Before we try to find the root cause, let's understand a keyword in IL called "box", which did the "Boxing". So, if you examine your IL code, you will absolutely found the box keyword. See below IL picture,

 

So, after you counted the box, you will see "3". And you will also notice that there is a Concat method?

Why there is a "Concat" method?

Please guess it by yourself.

 

Thanks.

转载于:https://www.cnblogs.com/lucasluo/archive/2010/12/11/1903014.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值