ArrayList是在System.Collections命名空间的一个类, 通过Add的方法添加一个项, 当进到这个类的元数据时, 可以看到这个方法的参数是一个object
public virtual int Add(object value)
所以在添加一个项时需要进行一次装箱的操作, 读取一个数据时需要一个拆箱的操作, 所以用ArrayList必然影响性能, 特别是项较多的时候进行读写, 至少要进行一次的装箱一次拆箱, 所花的时候也应该是更多
List<T>通过Add方法添加一个项是通过直接的类型来添加 public void Add(T item) 所以不需要再进行装箱与拆箱, 可以节省部分时间, 看下面的代码测试:
代码
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
//ArrayList
Stopwatch sw = new Stopwatch();
sw.Start();
ArrayList List1 = new ArrayList();
for (int i = 0; i < 10000; i++)
{
List1.Add(i);
}
Console.WriteLine("Add item done.");
foreach (int item in List1)
{
}
Console.WriteLine("Foreach item done.");
sw.Stop();
Console.WriteLine("ArrayList is need time:" + sw.ElapsedMilliseconds.ToString());
//List<int>
sw.Reset();
List<int> List2 = new List<int>();
for (int i = 0; i < 10000; i++)
{
List2.Add(i);
}
Console.WriteLine("Add item done.");
foreach (int item in List2)
{
}
Console.WriteLine("Foreach item done.");
sw.Stop();
Console.WriteLine("List<int> is need time:" + sw.ElapsedMilliseconds.ToString());
Console.ReadLine();
}
}
}
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
//ArrayList
Stopwatch sw = new Stopwatch();
sw.Start();
ArrayList List1 = new ArrayList();
for (int i = 0; i < 10000; i++)
{
List1.Add(i);
}
Console.WriteLine("Add item done.");
foreach (int item in List1)
{
}
Console.WriteLine("Foreach item done.");
sw.Stop();
Console.WriteLine("ArrayList is need time:" + sw.ElapsedMilliseconds.ToString());
//List<int>
sw.Reset();
List<int> List2 = new List<int>();
for (int i = 0; i < 10000; i++)
{
List2.Add(i);
}
Console.WriteLine("Add item done.");
foreach (int item in List2)
{
}
Console.WriteLine("Foreach item done.");
sw.Stop();
Console.WriteLine("List<int> is need time:" + sw.ElapsedMilliseconds.ToString());
Console.ReadLine();
}
}
}
当你运行看结果时你就知道相差的结果了, 所以在代码当中, 尽量使用List<int>来代替ArrayList