TrimToSize() Method
ลด Capacity ของ SortedList ให้เท่ากับ Count (จำนวน Elements จริง) เพื่อประหยัด Memory
ตัวอย่าง
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
SortedList sortedList = new SortedList();
// เพิ่ม 10 Items
for (int i = 1; i <= 10; i++)
{
sortedList.Add(i.ToString(), $"Value {i}");
}
Console.WriteLine($"Count: {sortedList.Count}"); // 10
Console.WriteLine($"Capacity: {sortedList.Capacity}"); // 16 (Default Growth)
// Trim Capacity ให้เท่ากับ Count
sortedList.TrimToSize();
Console.WriteLine($"Capacity (After Trim): {sortedList.Capacity}"); // 10
// แสดง Elements
Console.WriteLine("\nElements:");
foreach (DictionaryEntry entry in sortedList)
{
Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}
}
}
Output
Count: 10 Capacity: 16 Capacity (After Trim): 10 Elements: Key: 1, Value: Value 1 Key: 2, Value: Value 2 ... Key: 10, Value: Value 10
Capacity Growth Strategy
- SortedList เริ่มต้น Capacity = 0
- Add Item แรก → Capacity = 4
- เต็ม → Double Capacity (4→8→16→32→64...)
- เพื่อ Performance (Amortized O(1) Insert)
เมื่อไหร่ควร TrimToSize()
- ✅ หลัง Add/Remove เสร็จสิ้น ไม่มีการเพิ่มลบแล้ว
- ✅ Memory Critical Application
- ✅ ก่อน Serialize/Transfer (ลด Size)
- ❌ ไม่ควร Trim แล้ว Add ต่อ (จะ Reallocate ซ้ำ)
ArrayList และ List<T> ก็มี TrimToSize()
// ArrayList (Non-Generic)
ArrayList list = new ArrayList();
list.AddRange(new int[] { 1,2,3,4,5,6,7,8,9,10 });
list.TrimToSize();
// List (Generic)
List genericList = new List { 1,2,3,4,5,6,7,8,9,10 };
genericList.TrimExcess(); // Method Name ต่าง: TrimExcess()
SortedList<TKey, TValue> (Generic Version)
using System.Collections.Generic;
var sortedList = new SortedList();
for (int i = 1; i <= 10; i++)
sortedList.Add(i, $"Item {i}");
Console.WriteLine($"Count: {sortedList.Count}, Capacity: {sortedList.Capacity}");
// Capacity property ไม่ Expose ใน Generic Version (Internal)
// แต่ TrimExcess() ทำงานเหมือนกัน
sortedList.TrimExcess();
Non-Generic vs Generic
| Feature | SortedList (Non-Generic) | SortedList<TKey,TValue> (Generic) |
|---|---|---|
| Namespace | System.Collections | System.Collections.Generic |
| Capacity Property | Public | Internal (ไม่เข้าถึงได้) |
| Trim Method | TrimToSize() | TrimExcess() |
| Type Safety | Object/Boxing | Strongly Typed |
| Performance | ช้ากว่า (Boxing) | เร็วกว่า |
Best Practice
- ใช้
SortedList<TKey, TValue>(Generic) เป็นหลัก - TrimExcess() เมื่อเสร็จสิ้นการ Build Collection
- ระวัง: TrimExcess() ไม่รับประกัน Capacity = Count เสมอไป (Implementation Detail)