C#의 ArrayList에서 용량(Capacity)을 실제 요소 수에 맞게 줄이려면 TrimToSize() 메서드를 사용하면 됩니다.
ArrayList는 내부적으로 동적 배열을 사용하기 때문에, 요소를 추가할 때마다 필요 이상으로 큰 메모리 공간을 확보하게 됩니다. 예를 들어 요소가 9개뿐인데도 용량은 16으로 설정되어 있을 수 있습니다. 이때 TrimToSize()를 호출하면 사용하지 않는 여유 공간이 제거되어, 용량이 실제 저장된 요소 수(Count)와 동일해집니다.
메모리를 효율적으로 관리하고 싶다면, 리스트에 더 이상 요소를 추가하지 않을 시점에 이 메서드를 호출하는 것이 좋습니다.
예제 1
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
ArrayList list1 = new ArrayList();
list1.Add("A");
list1.Add("B");
list1.Add("C");
list1.Add("D");
list1.Add("E");
list1.Add("F");
list1.Add("G");
list1.Add("H");
list1.Add("I");
Console.WriteLine("Elements in ArrayList1...");
foreach (string res in list1) {
Console.WriteLine(res);
}
ArrayList list2 = new ArrayList();
list2.Add("A");
list2.Add("B");
list2.Add("C");
list2.Add("D");
list2.Add("E");
list2.Add("F");
list2.Add("G");
list2.Add("H");
list2.Add("I");
Console.WriteLine("Elements in ArrayList2...");
foreach (string res in list2) {
Console.WriteLine(res);
}
Console.WriteLine("Count of elements in ArrayList2 = " + list2.Count);
list2.RemoveAt(5);
Console.WriteLine("Count of elements in ArrayList2 (Updated) = " + list2.Count);
Console.WriteLine("Enumerator iterating the ArrayList2...");
IEnumerator demoEnum = list2.GetEnumerator();
while (demoEnum.MoveNext()) {
Console.WriteLine(demoEnum.Current);
}
Console.WriteLine("Capacity of ArrayList2 = " + list2.Capacity);
list2.TrimToSize();
Console.WriteLine("Capacity of ArrayList2 (updated) = " + list2.Capacity);
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Elements in ArrayList1... A B C D E F G H I Elements in ArrayList2... A B C D E F G H I Count of elements in ArrayList2 = 9 Count of elements in ArrayList2 (Updated) = 8 Enumerator iterating the ArrayList2... A B C D E G H I Capacity of ArrayList2 = 16 Capacity of ArrayList2 (updated) = 8
결과 분석
위 출력 결과를 보면 몇 가지 중요한 동작 방식을 확인할 수 있습니다.
- 요소를 하나 제거한 후
Count는 9에서 8로 줄어들었지만,Capacity는 그대로 16으로 유지됩니다. TrimToSize()호출 후에는 용량이 실제 요소 수인 8로 조정된 것을 확인할 수 있습니다.
예제 2
이번에는 요소를 삽입하는 경우를 포함한 또 다른 예제를 살펴보겠습니다.
using System;
using System.Collections;
public class Demo {
public static void Main() {
ArrayList list = new ArrayList();
list.Add("One");
list.Add("Two");
list.Add("Three");
list.Add("Four");
list.Add("Five");
list.Add("Six");
list.Add("Seven");
list.Add("Eight");
Console.WriteLine("ArrayList elements...");
foreach(string str in list) {
Console.WriteLine(str);
}
Console.WriteLine("ArrayList is read-only? = "+list.IsReadOnly);
Console.WriteLine("Does the element Six in the ArrayList? = "+list.Contains("Six"));
list.Insert(4, "Twelve");
Console.WriteLine("ArrayList elements...UPDATED");
foreach(string str in list) {
Console.WriteLine(str);
}
Console.WriteLine("Capacity of ArrayList = " + list.Capacity);
list.TrimToSize();
Console.WriteLine("Capacity of ArrayList (updated) = " + list.Capacity);
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
ArrayList elements... One Two Three Four Five Six Seven Eight ArrayList is read-only? = False Does the element Six in the ArrayList? = True ArrayList elements...UPDATED One Two Three Four Twelve Five Six Seven Eight Capacity of ArrayList = 16 Capacity of ArrayList (updated) = 9
결과 분석
- 8개의 요소를 추가했지만, ArrayList는 자동으로 용량을 16까지 늘려 미래의 추가 작업에 대비합니다.
Insert(4, "Twelve")를 통해 인덱스 4 위치에 새 요소가 삽입되고, 기존 요소들은 뒤로 밀려납니다.TrimToSize()실행 후 용량이 정확히 9(실제 요소 수)로 줄어든 것을 확인할 수 있습니다.
정리
TrimToSize() 메서드는 ArrayList의 불필요한 메모리 여유 공간을 제거하여 용량을 실제 요소 수와 일치시킵니다. 다만 주의할 점은, 이후에 요소를 다시 추가하면 ArrayList가 용량을 다시 늘리기 위해 내부 배열을 재할당해야 하므로 성능 저하가 발생할 수 있다는 점입니다. 따라서 리스트 구성이 완료된 후 더 이상 변경하지 않을 때 사용하는 것이 가장 효과적입니다.