装箱:是值类型转换为引用类型
拆箱:引用类型转换为值类型
引用类型:任何称为类 的类型都是引用类型,使用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.第二个是使代码更清晰和保证类型安全