拆箱和装箱

1、拆箱和装箱,我们都知道的是

装箱:就是将值类型转换为引用类型
拆箱:将引用类型转换为值类型

2、那么看下面一个例子:

string str=“123”
int n=Convert.ToInt32(str);

string是引用类型,int为值类型。那么,此处有没有发生拆装箱呢

答案是:没有

原因:看两种类型是否发生了装箱或拆箱,要看这两种类型是否存在继承关系。有继承关系才有可能
发生装箱和拆箱

3、现在,我们只知道拆装箱的定义,那么拆装箱到底给我们的应用程序带来了好处还是坏处呢?

我们可以看下面一段代码:

class Program
    {
        static void Main(string[] args)
        {
        //    int n = 10;
        //    object o = n;//装箱
        //    n = (int)o;//拆箱
            ArrayList list = new ArrayList();           
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 10000000; i++)
            {
                list.Add(i);//装箱10000000次用时约1.477
            }
            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Console.ReadKey();
            //List<int> list = new List<int>();
            //Stopwatch sw = new Stopwatch();
            //sw.Start();
            //for (int i = 0; i < 10000000; i++)
            //{
            //    list.Add(i);//无须装箱,用时0.12秒左右
            //}
            //sw.Stop();
            //Console.WriteLine(sw.Elapsed);
            //Console.ReadKey();
        }
    }

我们知道list集合所装的类型为object类型,因此在每次添加int类型数据时,都要进行装箱操作,而list<int>泛型集合类型为int,添加int类型数据时无须进行装箱操作

通过运行结果我们可以看出list集合进行同样数据的添加操作是所费时间明显高于list<>泛型集合。

因此拆装箱操作会影响(降低)我们应用程序的运行速度,故在开发中应该尽量避免拆装箱操作!

原文地址:https://www.cnblogs.com/hunternet/p/4717553.html