拆箱和装箱-性能测试

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using Debug = UnityEngine.Debug;

//装箱:值类型转换为引用类型
//拆箱:引用类型转换为值类型
//引用类型:任何称之为"类"的类型都是引用类型 使用class修饰 string object
//值类型:所有值类型都称为结构或枚举,使用struct或enum修饰 int float double char


public class Test : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int count = 100000000;
        Stopwatch t1=new Stopwatch();
        Stopwatch t2=new Stopwatch();
        Stopwatch t3=new Stopwatch();
        t1.Start();
        List<int>l=new List<int>();
        for (int i = 0; i < count; i++)
        {
            l.Add(i);//不发生装箱操作
            int x = l[i];//不发生拆箱操作
        }
        t1.Stop();
        Debug.Log("List time"+t1.ElapsedMilliseconds+"ms");
        
        t2.Start();
        ArrayList a=new ArrayList();
        for (int i = 0; i < count; i++)
        {
            a.Add(i);//发生装箱操作 int转为object 值类型转换为引用类型
            int b = (int)a[i];//发生拆箱操作 object(引用类型)强转为值类型(int)
        }
        t2.Stop();
        Debug.Log("ArrayList time"+t2.ElapsedMilliseconds+"ms");

        t3.Start();
        ArrayList e=new ArrayList();
        for (int i = 0; i < count; i++)
        {
            e.Add("X");//不发生装箱操作            
            string f = e[i].ToString();//不发生拆箱操作        }
        t3.Stop();
        Debug.Log("ArrayList1 time"+t3.ElapsedMilliseconds+"ms");
    }
    //测试结果 List time1902ms  ArrayList time8187ms ArrayList1 time3547ms
    //数据表明 泛型数组有两个优势
    //1.对于存储值类型数据,性能更优
    //2.使代码更清晰和保证类型的安全 因为类型是声明的时候就指定
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值