博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
(.NET) Boxing and Unboxing
阅读量:5358 次
发布时间:2019-06-15

本文共 2151 字,大约阅读时间需要 7 分钟。

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

你可能感兴趣的文章
参数快照以及参数订阅
查看>>
显示域初始化
查看>>
我的编程学习日志(7)--typedef的扩展
查看>>
Html/CSS 初步介绍html和css部分重要标签
查看>>
static 静态
查看>>
【剑指offer】33、二叉搜索树的后序遍历序列
查看>>
svn 基本操作
查看>>
Hyper-v虚拟机联网配置
查看>>
python链表的实现
查看>>
logging模块
查看>>
Alfresco 4.0.d 的同步多个ldap信息问题
查看>>
SpringCloud知识点20190313
查看>>
c#中的Cache缓存技术
查看>>
Oracle 给已创建的表增加自增长列
查看>>
《DSP using MATLAB》Problem 2.17
查看>>
if 循环
查看>>
uva 111 History Grading(lcs)
查看>>
Python学习week2-python介绍与pyenv安装
查看>>
php判断网页是否gzip压缩
查看>>
一个有意思的js实例,你会吗??[原创]
查看>>