當採用預設建構函式List<int> value = new List<int>();執行個體化一個List<T>對象時,.Net Framework只是在記憶體中申請了一塊記憶體來存放List<T>對象本身(不包含List當中的Items元素)。
當為List<T>對象添加第一個Item元素時,List<T>對象會申請能儲存4個Item元素的記憶體空間,然後將Item元素存放在申請的空間裡。
List<T>對象有一個Capacity屬性用來表示當前List<T>對象的容量(即當前用於存放Item的記憶體空間能存放的Item的個數),可以手動的設定它來設定List<T>的容量(Capacity的改變將會導致重新申請記憶體)。
當List<T>對象的Item元素數量超過了Capacity的數量時,List<T>對象會重新申請一塊大小是原來Capacity的兩倍的記憶體空間,然後將當前所有Item元素以及待添加元素複製到新的記憶體空間中。
通過下列測試代碼可以驗證List<T>的記憶體配置原則:
List<int> value = new List<int>(4);//此時 Count:0 Capacity: 4 for (int i = 1; i <= 5; i++){ value.Add(i);}//此時 Count:5 Capacity: 8 value.TrimExcess();//此時 Count:5 Capacity: 5 //remove an itemvalue.RemoveAt(4);//此時 Count:4 Capacity: 5value.TrimExcess();//此時 Count:4 Capacity: 5---------------Capacity為什麼不是4呢?請高手指點
//remove another itemvalue.RemoveAt(1);//此時 Count:3 Capacity: 5value.TrimExcess();//此時 Count:3 Capacity: 3value.Clear();//此時 Count:0 Capacity: 3value.TrimExcess();//此時 Count:0 Capacity: 0
知道了記憶體配置的原則,接下來就得根據這些原則來採用最優的方法保證有限的記憶體空間能得到合理的運用。歸納起來主要有如下幾點:
- 當執行個體化一個List<T>對象時,如果能預知其Item元素的大致個數,應該在執行個體化一個List<T>對象的時候設定其Capacity值為接近於Item元素個數的最小值。這樣的話可以避免在向List<T>中添加元素的時候,不斷的申請記憶體與元素的複製。
- 當由於不斷的調用Remove方法而導致Item元素的個數遠遠小於Capacity,就會造成記憶體的浪費。此時可以調用TrimExcess方法釋放多餘的記憶體。
【附】如下為MSDN中List類中的部分屬性和成員:
// 摘要:// 擷取或設定該內部資料結構在不調整大小的情況下能夠容納的元素總數。//// 返回結果:// 在需要調整大小之前 System.Collections.Generic.List<T> 能夠容納的元素的數目。//// 異常:// System.ArgumentOutOfRangeException:// System.Collections.Generic.List<T>.Capacity 設定為小於 System.Collections.Generic.List<T>.Count// 的值。//// System.OutOfMemoryException:// 系統中沒有足夠的可用記憶體。public int Capacity { get; set; }//// 摘要:// 擷取 System.Collections.Generic.List<T> 中實際包含的元素數。//// 返回結果:// System.Collections.Generic.List<T> 中實際包含的元素數。public int Count { get; }// 摘要:// 將對象添加到 System.Collections.Generic.List<T> 的結尾處。//// 參數:// item:// 要添加到 System.Collections.Generic.List<T> 的末尾處的對象。對於參考型別,該值可以為 null。public void Add(T item);//// 摘要:// 從 System.Collections.Generic.List<T> 中移除特定對象的第一個匹配項。//// 參數:// item:// 要從 System.Collections.Generic.List<T> 中移除的對象。對於參考型別,該值可以為 null。//// 返回結果:// 如果成功移除 item,則為 true;否則為 false。如果在 System.Collections.Generic.List<T> 中沒有找到// item,該方法也會返回 false。[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]public bool Remove(T item);//// 摘要:// 將容量設定為 System.Collections.Generic.List<T> 中的實際元素數目(如果該數目小於某個閾值)。public void TrimExcess();