FunctionGHW

立志成为真正程序员的码农,伪全栈,目前主要写C#

C#中值类型的装箱(boxing)和拆箱(unboxing)

FunctionGHW posted @ 2014年3月17日 17:57 in C#与.Net with tags c# 装箱 boxing 拆箱 unboxing , 4256 阅读

在C#中,把一个值类型转化成引用类型的过程称为装箱(boxing)。这个引用类型可以是object类型,也可以是此值类型实现的任何接口类型。

        int num = 5;
        //引起装箱操作
        object o = num;
        

CLR会把值类型包装在一个对象内部。装箱的过程大致如下:

  1. 像创建其他引用类型的实例一样,在托管堆上为新对象分配需要的内存。
  2. 将值类型的字段值复制到新对象的对应字段。
  3. 返回这个对象的引用。

拆箱(Unboxing)的过程简单些。拆箱就是从一个装箱后的对象里获得一个指针的过程,这个指针指向该对象中的值类型的字段。拆箱之后往往都伴随着字段的复制(比如赋值操作):

        int val = (int)o;
        

现在大家基本上都是说装箱/拆箱机制的缺点,其缺点至少有:

  • 装箱拆箱都需要额外的计算,影响性能。
  • 装箱需要消耗的托管堆内存,如果有大量的对象产生,会增加GC的压力。
  • 增加代码中强制类型转换操作的次数,增加出错的可能性。

一句话,装箱/拆箱操作对程序的运行速度和内存消耗都很不利,应该尽量避免

既然如此,这个机制为什么还要存在呢?所谓引用类型变量,其实是在线程栈上存放一个引用, 引用指向托管堆上的某个对象。假设这样一个场景,有一个方法的一个参数的类型是object, 也就是对任何类型都通用,object是引用类型,所以调用时就需要传递一个引用。 值类型也是object的分支,所以值类型也可以作为object才对,但是值类型的值是在线程栈上的, 因此为了保证代码能正常工作,就需要把这个值类型"放"到堆上,变成引用类型。

这样看来,所有含有object类型的参数的方法, 都存在引起装箱操作的可能。例如:

        ArrayList ary_lst = new ArrayList();
        ary_lst.Add(2014);// Add(object), 引起装箱
        

感觉上面的示例太过鸡肋,我们换一个。字符串的拼接操作大家用的很多吧, 估计有很多人和我一样随手就用起来了。

        int num = 5;
        string str = "the number is" + num;
        

连接操作会调用System.String.Concat()方法, 最匹配的一个重载是Concat(object, object)num是值类型,因此引起装箱操作,然后Concat方法内部会调用两个对象的ToString()方法,得到两个string,最后调用另一个重载方法Concat(string, string)。装箱操作所产生的"临时对象",对我们一点用也没有, 我们只是想要字符串"5"而已,所以可以这样做:

        int num = 5;
        //不会引起装箱
        string str = "the number is" + num.ToString();
        

因为操作数都是sting类型, 所以会直接调用Concat(string, string),既没有引起不必要的装箱,又少拐了一个弯。

String.Format()方法也存在这样的问题。

        //会引起装箱
        string str2 = string.Format("The number is {0}", 9);
        //不会引起装箱
        string str3 = string.Format("The number is {0}", 9.ToString());
        

 

Liwovosa 说:
2021年4月12日 23:30

If you set out to make me think today; mission accomplished! I really like your writing style and how you express your ideas. Thank you. 123movies websites

Liwovosa 说:
2021年4月13日 19:39

Interesting and amazing how your post is! It Is Useful and helpful for me That I like it very much, and I am looking forward to Hearing from your next.. online casino

SmithSeo 说:
2021年4月17日 17:17

Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. A Different Version

SmithSeo 说:
2021年4月17日 17:18

An interesting dialogue is price comment. I feel that it is best to write more on this matter, it may not be a taboo topic however usually individuals are not enough to talk on such topics. To the next. Cheers. nama nama situs judi slot online

SmithSeo 说:
2021年4月19日 05:56

You completed a few fine points there. I did a search on the subject and found nearly all persons will go along with with your blog. Training Canberra

jackjohnny 说:
2021年6月02日 16:29

Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. indian visa online

johnyking 说:
2021年6月16日 18:58

If you set out to make me think today; mission accomplished! I really like your writing style and how you express your ideas. Thank you. 먹튀검증

jackjohnny 说:
2021年6月17日 22:18

Thank you again for all the knowledge you distribute, Good post. I was very interested in the article, it's quite inspiring I should admit. I like visiting you site since I always come across interesting articles like this one. Great Job, I greatly appreciate that. Do Keep sharing! Regards, <a href="https://totogle.com/">먹튀검증</a>

eyeshadow 说:
2021年6月25日 18:46

I personally use them exclusively high-quality elements : you will notice these folks during:

jackjohnny 说:
2021年6月26日 21:31

We have sell some products of different custom boxes.it is very useful and very low price please visits this site thanks and please share this post with your friends. 토토사이트

jackjohnny 说:
2021年6月27日 17:05

I am impressed. I don't think Ive met anyone who knows as much about this subject as you do. You are truly well informed and very intelligent. You wrote something that people could understand and made the subject intriguing for everyone. Really, great blog you have got here. Paypal SMM panel

jackjohnny 说:
2021年6月28日 16:24

We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work. voyance telephone gaia

jackjohnny 说:
2021年6月29日 18:14

hi was just seeing if you minded a comment. i like your website and the thme you picked is super. I will be back. indian visa on arrival

jackjohnny 说:
2021年7月05日 18:45

Very informative post! There is a lot of information here that can help any business get started with a successful social networking campaign. สล็อต

jackjohnny 说:
2021年7月11日 17:37

This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. 토토사이트

jackjohnny 说:
2021年7月13日 19:15

this is really nice to read..informative post is very good to read..thanks a lot! Brawl Stars Hack 2021

jackjohnny 说:
2021年7月14日 22:44

ikinci el cikma enjektör bosch kullanilmis oto enjektör satin al ikinci el enjektör

johnyking 说:
2021年7月15日 23:14

Pretty nice post. I just stumbled upon your weblog and wanted to say that I have really enjoyed browsing your blog posts. After all I’ll be subscribing to your feed and I hope you write again soon! scarlett johansson body measurements

Rafay 说:
2021年8月09日 04:29

Https://www.propassion.net

Website hosting bh

johnyking 说:
2021年8月21日 20:29

All the contents you mentioned in post is too good and can be very useful. I will keep it in mind, thanks for sharing the information keep updating, looking forward for more posts.Thanks 먹튀폴리스

johnyking 说:
2021年8月30日 00:08

I really thank you for the valuable info on this great subject and look forward to more great posts. Thanks a lot for enjoying this beauty article with me. I am appreciating it very much! Looking forward to another great article. Good luck to the author! All the best! Search Websites

johnyking 说:
2021年9月14日 15:38

Thanks for the nice blog. It was very useful for me. I'm happy I found this blog. Thank you for sharing with us,I too always learn something new from your post. Sexy baccarat

johnyking 说:
2021年9月15日 16:55

This article was written by a real thinking writer without a doubt. I agree many of the with the solid points made by the writer. I’ll be back day in and day for further new updates. Pkv Games

johnyking 说:
2021年9月16日 02:22

Please let me know if you’re looking for a article writer for your site. You have some really great posts and I feel I would be a good asset. If you ever want to take some of the load off, I’d absolutely love to write some material for your blog in exchange for a link back to mine. Please send me an email if interested. Thank you! Animefenix

johnyking 说:
2021年9月16日 19:06

Cool stuff you have got and you keep update all of us. บาคาร่า-บิกินี่

johnyking 说:
2021年10月06日 23:29

This particular papers fabulous, and My spouse and i enjoy each of the perform that you have placed into this. I’m sure that you will be making a really useful place. I has been additionally pleased. Good perform! how to sell merchant processing

johnyking 说:
2021年10月07日 03:08

Thanks for sharing us. SEO LIMA

johnyking 说:
2021年10月07日 13:17

Excellent and very exciting site. Love to watch. Keep Rocking. AGENCIA SEO

johnyking 说:
2021年10月07日 23:20

Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. North American Bancard Agent

johnyking 说:
2021年10月08日 18:54 Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. how to sell credit card processing
johnyking 说:
2021年10月18日 02:33

I would like to say that this blog really convinced me to do it! Thanks, very good post. เคดิตฟรี ยืนยันเบอร์

johnyking 说:
2021年10月19日 23:42 I recently found many useful information in your website especially this blog page. Among the lots of comments on your articles. Thanks for sharing. esteroides
johnyking 说:
2021年10月28日 23:43 I am definitely enjoying your website. You definitely have some great insight and great stories. naza
johnyking 说:
2021年12月13日 21:22

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. Hole in One Insurance

johnyking 说:
2021年12月21日 19:14 Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. podcast transcription service
johnyking 说:
2021年12月21日 19:14 Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. podcast transcription service
pg slot ทดลองเล่น 说:
2022年3月10日 08:20

I see some amazingly important and kept up to length of your strength searching for in your on the site

us canada 说:
2022年4月09日 08:06

It was a very good post indeed. I thoroughly enjoyed reading it in my lunch time. Will surely come and visit this blog more often. Thanks for sharing.

asia99th 说:
2022年5月09日 07:12

Very nice blog and articles. I am realy very happy to visit your blog. Now I am found which I actually want. I check your blog everyday and try to learn something from your blog. Thank you and waiting for your new post. asia99th

johnyking 说:
2022年5月11日 03:14 This article was written by a real thinking writer. I agree many of the with the solid points made by the writer. I’ll be back. Slim N Lift For Men in Pakistan
เว็บพนันออนไลน์ 说:
2022年5月13日 09:39

Hi! This is my first visit to your blog! We are a team of volunteers and new initiatives in the same niche. Blog gave us useful information to work. You have done an amazing job! เว็บพนันออนไลน์

johny 说:
2022年6月24日 22:22

Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. Auto Miner 1.19


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter