C#装箱和拆箱,泛型和非泛型比较。

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

        引用类型:任何称为类 的类型都是引用类型,使用class修饰
            如:string object

        值类型:所以值类型都称为结构或者枚举,使用struct或enum修饰
             如:int float double char

简单的了解了什么是装箱拆箱后
现在我们来看ArrayList和泛型的一个简单对比 看代码

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 泛型和动态数组比较
{
    class Program
    {
        static void Main(string[] args)
        {
        //#region装箱:是值类型转换为引用类型   
            //拆箱:引用类型转换为值类型

            //引用类型:任何称为类 的类型都是引用类型,使用class修饰
            //    如:string object

            //值类型:所以值类型都称为结构或者枚举,使用struct或enum修饰
            //     如:int float double char
        //#endregion
            int n = 10000000;
            //创建计时器
            Stopwatch t1 = new Stopwatch();
            Stopwatch t2 = new Stopwatch();
            Stopwatch t3 = new Stopwatch();
            Stopwatch t4 = new Stopwatch();
            //泛型动态数组 list
            Console.WriteLine("测试值类型对象int");
            t1.Start();
            List<int> list = new List<int>();
            for (int i = 0; i < n; i++)
            {
                list.Add(i);  //不发生装箱
                int x = list[i];//不发生拆箱

            }
            t1.Stop();
            Console.WriteLine("List time :{0} ms",t1.ElapsedMilliseconds);

            t2.Start();
            ArrayList a = new ArrayList();
            for (int i = 0; i < n; i++)
            {
                a.Add(i);  //发生装箱
                int x = (int)a[i]; //发生拆箱
            }
            t2.Stop();
            Console.WriteLine("ArrayList time :{0} ms", t2.ElapsedMilliseconds);


            Console.WriteLine("测试引用类型对象string");
            t3.Start();
            List<string> list2 = new List<string>();
            for (int i = 0; i < n; i++)
            {
                list2.Add("x");  //不发生装箱
                string x = list2[i];//不发生拆箱

            }
            t3.Stop();
            Console.WriteLine("List time :{0} ms", t3.ElapsedMilliseconds);

            t4.Start();
            ArrayList a2 = new ArrayList();
            for (int i = 0; i < n; i++)
            {
                a2.Add("x");  //不发生装箱
                string x = (string)a2[i]; //不发生拆箱    因为Object和string都是引用类型
            }
            t4.Stop();
            Console.WriteLine("ArrayList time :{0} ms", t4.ElapsedMilliseconds);

            Console.Read();

            //总结
            //泛型数组List有俩个优势
            //    1.第一个是对于存储值类型数据,性能更优
            //    2.第二个是使代码更清晰和保证类型安全
        }
    }
}

结果:

在这里插入图片描述

//总结
//泛型数组List有俩个优势
// 1.第一个是对于存储值类型数据,性能更优
// 2.第二个是使代码更清晰和保证类型安全

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值