ArrayList 屬第一代集合,元素型別為 object,導致三大問題:
foreach (int item in al) 隱含 (int) 轉型InvalidCastException// 非泛型 ArrayList al = new ArrayList(); al.Add(1); // 裝箱 int t = (int)al[0]; // 拆箱+轉型 // 泛型 Listlist = new List (); list.Add(1); // 無裝箱 int t = list[0]; // 無拆箱、無轉型
| 集合類型 | 耗時(ms) | GC 次數(Gen 0) |
|---|---|---|
| ArrayList | 2375 | 26 |
| List<int> | 220 | 5 |
泛型快 10 倍,GC 壓力降 80%。
ArrayList.InsertRange 內部:建立 object[] → CopyTo → 再 CopyTo 到內部陣列,全程裝箱/拆箱。
List<T> 直接操作 T[],零額外分配。
System.Collections (ArrayList, Hashtable, Queue, Stack)System.Collections.Generic (List<T>, Dictionary<TKey,TValue>, Queue<T>, Stack<T>)Listlist = new List (); list.Add(1); list.Add(2); // list.Add("mike"); // 編譯錯誤:無法從 string 轉換為 int
預設用泛型集合。只有在明確需要異構儲存時,才考慮非泛型或
List<object>。
本系列持續更新至建議 157,歡迎持續關注。