ArrayList 存 object,值類型頻繁裝箱/拆箱,且無型別安全。List<T> 以強型別陣列為底層,完全消除此問題,是效能與可維護性的雙重升級。
// 非泛型
var a = new ArrayList(); a.Add(1); a.Add(2); // 裝箱
foreach (int i in a) Console.WriteLine(i); // 拆箱
// 泛型
var l = new List<int>(); l.Add(1); l.Add(2); // 無裝箱
foreach (int i in l) Console.WriteLine(i); // 直接讀取
| ArrayList | List<T> | 備註 |
|---|---|---|
| Capacity / Count / Item | Capacity / Count / Item | 完全對應 |
| Add / AddRange / Clear | Add / AddRange / Clear | 完全對應 |
| BinarySearch / Sort / Reverse | BinarySearch / Sort / Reverse | 完全對應 |
| Clone | GetRange(0, Count) | 淺拷貝替代 |
| IsFixedSize / IsReadOnly / IsSynchronized / SyncRoot | ((IList)list).xxx | 顯式轉 IList 存取,前兩者永回 false |
| Repeat | 自寫 for+Add | 無對應靜態方法 |
| FixedSize / ReadOnly / Synchronized | AsReadOnly / lock / 無 | 官方移除同步包裝,建議自行 lock |
var copy = oldList.GetRange(0, oldList.Count); // 淺拷貝所有元素
public static void Repeat<T>(this List<T> list, T item, int count) {
for (int i=0; i<count; i++) list.Add(item);
}
ArrayList 預設 16List<T> 預設 4new List<T>(estimatedCount) 避免多次擴容。舊碼 ArrayList.Synchronized(list) → 新碼 lock(list) { ... } 或改用 System.Collections.Concurrent 命名空間。
百萬級整數加入測試:List<int> 比 ArrayList 快 2-3 倍,記憶體佔用降低 50% 以上(無裝箱物件頭)。
將 ArrayList 全面替換為 List<T> 是零風險、高報酬的重構動作,建議納入程式碼審查清單強制執行。