CLR via c# 装箱与拆箱
来源:互联网 发布:python实现二叉树 编辑:程序博客网 时间:2024/05/21 09:33
using System;namespace 拆箱装箱{ class Program { class someref { public Int32 x;} //class是引用类型,在托管堆上分配内存 //int32和int是相同的,在clr中int就是32位的,不会因为32位或64位系统而改变。 struct someval { public Int32 x; } //struct是值类型,在线程栈中分配内存 static void Main(string[] args) { someref r1 = new someref(); someval v1 = new someval(); r1.x = 5; v1.x = 5; Console.WriteLine(r1.x);//显示“5” Console.WriteLine(v1.x);//显示“5” someref r2 = r1;//在线程栈上分配了一个内存,将值复制过去 someval v2 = v1;//将对象v1在托管堆的地址,给v2。所以v1,v2指向同一个对象 r1.x = 8; v1.x = 9; Console.WriteLine(r1.x);//显示“8” Console.WriteLine(v1.x);//显示“9” Console.WriteLine(r2.x);//显示“8” Console.WriteLine(v2.x);//显示“5” Console.ReadLine(); } }}
using System;namespace 装箱与拆箱1{ class Program { static void Main(string[] args) { int v = 5; object o = v;//第一次装箱 v = 123; Console.WriteLine(v+","+(int) o);//两次装箱 //调用的是string的静态方法 public string concat(object arg0,object arg1,object arg2); //v进行了一次装箱,(int)o先拆箱在装箱,装箱的开销远低于拆箱。对于c#来说,object是 //万物之母,一切类型都是对象。所以理论上来说,所有的内存开销都应该在托管堆中分配,但是这样 //的代价太大:托管堆速度比较慢,额外的内存开销,垃圾回收开销。因此,为了提升简单的,常用的 //类型的性能,CLR提供了名为“值类型”的轻量级类型。 //轻型主要归结于以下两个原因 //1.它们不在托管堆上分配 //2.它们没有堆上的每个对象都有的额外成员,即“类型对象指针”和“同步快索引” Console.ReadLine(); } }}//CLR via c# p117
using System;using System.Diagnostics;namespace 装箱与拆箱2{ class Program { static void Main(string[] args) { int a = 1, b = 1, c = 1; Stopwatch st = new Stopwatch(); /*st.Start(); for (int i = 0; i < 10000; i++) Console.WriteLine("{0},{1},{2}", a, b, c);//三次装箱 st.Stop(); Console.WriteLine(st.ElapsedMilliseconds);//消耗的时间为500ms */ st.Start(); string s1 = a.ToString(); string s2 = b.ToString(); string s3 = c.ToString(); for (int i = 0; i < 10000; i++) Console.WriteLine(s1+s2+s3); st.Stop(); Console.WriteLine(st.ElapsedMilliseconds);//消耗的时间为450ms Console.ReadLine(); /*理论上说第一次消耗的资源时间比第二次多,测试中也可以大致看出时间确实减少了*/ } }}