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.使代码更清晰和保证类型的安全 因为类型是声明的时候就指定 }
拆箱和装箱-性能测试
最新推荐文章于 2024-06-01 00:04:05 发布
453

被折叠的 条评论
为什么被折叠?



