[C#性能简析]-集合容量的指定

长度动态增加的集合类,例如 ArrayList、Queue等,无需在初始化时指定其容量,集合本身能够根据需求自动增加集合大小,为程序设计带来方便。然而,过分依赖这种特性对程序的性能提高并非好的选择,因为集合动态增加的过程是一个内存重新分配和集合元素复制的过程,会对性能造成一定的影响,所以有必要在集合初始化时指定一个适当的容量。

下面分三种情况来测试指定集合容量对程序性能的影响。

 (感谢zhenway的意见,下面是本人修改后的测试码)

 

修改后的代码
1 using System;
2  using System.Collections.Generic;
3  using System.Text;
4  using System.Collections;
5  using System.Diagnostics;
6
7 namespace Test_Console
8 {
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 Stopwatch sw = new Stopwatch();
14
15 // 情况一:不指定数组的长度...................................
16
17 sw.Start();
18
19 for (int i = 0; i < 10000; i++)
20 {
21 ArrayList al = new ArrayList();
22
23 for (int j = 0; j < 100; j++)
24 {
25 al.Add("NewItem");
26 }
27 }
28
29 sw.Stop();
30 Console.WriteLine(sw.ElapsedMilliseconds + " 毫秒");
31 sw.Reset();
32
33 // 情况二:初始化时为集合对象指定合适的大小................
34
35 sw.Start();
36
37 for (int i = 0; i < 10000; i++)
38 {
39 ArrayList al = new ArrayList(105);
40
41 for (int j = 0; j < 100; j++)
42 {
43 al.Add("NewItem");
44 }
45 }
46
47 sw.Stop();
48 Console.WriteLine(sw.ElapsedMilliseconds + " 毫秒");
49 sw.Reset();
50
51 // 情况三:初始化时为集合对象指定容量,容量不足时需重新分配
52
53 sw.Start();
54
55 for (int i = 0; i < 10000; i++)
56 {
57 ArrayList al = new ArrayList(4);
58
59 for (int j = 0; j < 100; j++)
60 {
61 al.Add("NewItem");
62 }
63 }
64
65 sw.Stop();
66 Console.WriteLine(sw.ElapsedMilliseconds + " 毫秒");
67 }
68 }
69 }

 

 

运行结果如下:

 

由以上运行结果不难发现:

  1. 指定一个适当的容量对性能提高来说是最好的选择;

  2. 在不容易确定集合的容量时,如果设定的容量太小,反而对程序的执行效率产生负面影响。

posted @ 2010-02-22 23:18  刘笨笨  阅读(797)  评论(5编辑  收藏  举报