学习自bilbili网站UP主:离忧夏天
泛型数组List有两个优势:
- 对于存储值类型数据的话,性能更优
- 代码更清晰和保证类型安全(如果我指定了是int类型,但是我存储了string类型,那么就会报错)
class Program
{
public static void Main(string[] args)
{
int N = 1000000;
Stopwatch t1 = new Stopwatch();
Stopwatch t2 = new Stopwatch();
t1.Start();
List<int> l = new List<int>();
for (int i = 0; i < N; i++)
{
//因为泛型List指定了存储对象类型是int值类型,所以不需要装箱和拆箱
l.Add(i);
int temp = l[i];
}
t1.Stop();
Console.WriteLine("泛型对值类型数据:"+t1.ElapsedMilliseconds+"ms");
t2.Start();
ArrayList a = new ArrayList();
for (int i = 0; i < N; i++)
{
//因为ArrayList存储的数据是Object对象
a.Add(i); //需要装箱
int temp=(int)a[i]; //需要拆箱
}
t2.Stop();
Console.WriteLine("非泛型对值类型数据:"+t2.ElapsedMilliseconds+"ms");
}
}
---------------------------------------------------------------------------------------
泛型数组对值类型数据:8ms
非泛型数组对值类型数据:70ms
以上明显可以看出来非泛型ArrayList对于存储值类型的数据的速度是比泛型List要慢的多。
ArrayList存储数据是Object对象,进行装箱,取数据的时候要拆箱,消耗性能。
class Program
{
public static void Main(string[] args)
{
int N = 1000000;
Stopwatch t1 = new Stopwatch();
Stopwatch t2 = new Stopwatch();
t1.Start();
List<string> l = new List<string>();
for (int i = 0; i < N; i++)
{
//因为泛型List指定了存储对象类型是string引用类型,所以不需要装箱和拆箱
l.Add("test");
string temp = l[i];
}
t1.Stop();
Console.WriteLine("泛型对引用类型数据:"+t1.ElapsedMilliseconds+"ms");
t2.Start();
ArrayList a = new ArrayList();
for (int i = 0; i < N; i++)
{
//因为ArrayList存储的数据是Object引用类型对象,string也是引用类型对象,所以不会发生装箱
a.Add("test"); //不装箱
string temp=(string)a[i]; //不拆箱
}
t2.Stop();
Console.WriteLine("非泛型对引用类型数据:"+t2.ElapsedMilliseconds+"ms");
}
}
---------------------------------------------------------------------------------------
泛型对引用类型数据:10ms
非泛型对引用类型数据:12ms
可以看出同样对引用类型数据进行存储,泛型List和非泛型ArrayList的存储速度相差不大。