[C#效能簡析]-集合容量的指定

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.