ArrayList.TrimToSize() Method
ลด Capacity ให้เท่ากับ Count จริง เพื่อปล่อย Memory ที่ไม่ได้ใช้
ตัวอย่างพื้นฐาน
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
ArrayList list = new ArrayList();
// Add 9 items
for (char c = 'A'; c <= 'I'; c++)
list.Add(c.ToString());
Console.WriteLine($"Count: {list.Count}"); // 9
Console.WriteLine($"Capacity: {list.Capacity}"); // 16 (Growth Strategy)
// Remove 1 item
list.RemoveAt(5); // Remove 'F'
Console.WriteLine($"Count after Remove: {list.Count}"); // 8
Console.WriteLine($"Capacity after Remove: {list.Capacity}"); // 16 (ไม่ลดอัตโนมัติ)
// Trim
list.TrimToSize();
Console.WriteLine($"Capacity after Trim: {list.Capacity}"); // 8
}
}
Output
Count: 9 Capacity: 16 Count after Remove: 8 Capacity after Remove: 16 Capacity after Trim: 8
Enumerator Example
ArrayList list = new ArrayList { "A", "B", "C", "D", "E" };
list.RemoveAt(2); // Remove "C"
Console.WriteLine("Enumerator:");
IEnumerator enum = list.GetEnumerator();
while (enum.MoveNext())
{
Console.WriteLine(enum.Current);
}
Output
Enumerator: A B D E
ArrayList Capacity Growth
- Start: Capacity = 0
- Add 1st: Capacity = 4
- Full → Double: 4→8→16→32→64→128...
- Remove: Capacity ไม่ลดอัตโนมัติ
TrimToSize() vs TrimExcess()
| Collection | Method | Namespace |
|---|---|---|
| ArrayList | TrimToSize() | System.Collections |
| List<T> | TrimExcess() | System.Collections.Generic |
| SortedList (Non-Generic) | TrimToSize() | System.Collections |
| SortedList<TKey,TValue> | TrimExcess() | System.Collections.Generic |
| Queue / Stack | TrimToSize() / TrimExcess() | Both Versions |
เมื่อไหร่ควรใช้ TrimToSize()
- ✅ หลังจาก Build Collection เสร็จ ไม่ Add/Remove อีก
- ✅ Memory Constrained Environment
- ✅ ก่อน Serialize/Network Transfer
- ❌ ใน Loop ที่ Add/Remove บ่อย (Overhead มากกว่าประโยชน์)
Modern Alternative: List<T>
✅ ใช้ List<T> แทน ArrayList
- Type Safety (No Boxing/Unboxing)
- Performance ดีกว่า
- TrimExcess() ทำงานเหมือนกัน
- LINQ Support เต็มรูปแบบ
- Type Safety (No Boxing/Unboxing)
- Performance ดีกว่า
- TrimExcess() ทำงานเหมือนกัน
- LINQ Support เต็มรูปแบบ
// Modern Way
var list = new List { "A", "B", "C", "D", "E" };
list.RemoveAt(2);
list.TrimExcess(); // Capacity = Count
Capacity Property
// Get/Set Capacity (List)
List list = new List();
list.Capacity = 100; // Pre-allocate (Avoid Resize)
list.Add(1); // Count=1, Capacity=100
// ArrayList
ArrayList aList = new ArrayList();
aList.Capacity = 100; // Same