長度動態增加的集合類,例如 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. 在不容易確定集合的容量時,如果設定的容量太小,反而對程式的執行效率產生負面影響。