比较 ArrayList 与 List Of T 之间性能究竟有多大的差别

闲的蛋疼,每天一搏,测试了一下两个集合容器之间性能的差异: ArrayList是一个弱类型的集合列表,每次对其进行操作的时候,不论是存储还是读取,我们都需要经过一次强制类型转换(“装箱/拆箱”)操作才能够正常使用,一两次没有什么问题,但到达一个数量级之后,速度成指数级别变化。 还好在C#2之后引入了强类型集合List,免除了大量数据的集合进行操作的时候性能问题。 测试代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
ArrayList _oldList = new ArrayList();
List<int> _newList = new List<int>();

Stopwatch _timerOld = new Stopwatch();
Stopwatch _timerNew = new Stopwatch();
_timerOld.Start();
for(int i = 0;i<9999999;i++)
{
        _oldList.Add(i);
}
for(int j = 0;j<_oldList.Count;j++)
{
        _oldList[j] = (int)_oldList[j] + 1;
}
_timerOld.Stop();
Console.WriteLine("ArrayList所用时间:{0}", _timerOld.ElapsedMilliseconds);
            
_newList.Start();
for (int i = 0;i<9999999;i++)
{
         _newList.Add(i);
}
for (int j = 0; j < _newList.Count; j++)
{
         _newList[j] = (int)_newList[j] + 1;
}
_timerNew.Stop();
Console.WriteLine("List<int>所用时间:{0}", _timerNew.ElapsedMilliseconds);

QQ截图20170321215651.png

Licensed under CC BY-NC-SA 4.0
Built with Hugo
主题 StackJimmy 设计