C#에서 지정된 초기 크기를 가지는 HybridDictionary를 생성하려면 생성자에 초기 크기를 인수로 전달하면 됩니다.
HybridDictionary란?
HybridDictionary는 컬렉션의 크기가 작을 때는 내부적으로 ListDictionary를 사용하고, 컬렉션이 일정 크기 이상으로 커지면 자동으로 Hashtable로 전환되는 컬렉션입니다. 저장할 요소의 개수를 미리 알고 있다면 초기 크기를 지정하여 성능을 최적화할 수 있습니다.
예제 1: 초기 크기 5로 생성하기
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main(){
HybridDictionary dict = new HybridDictionary(5);
dict.Add("A", "AB");
dict.Add("B", "BC");
dict.Add("C", "DE");
dict.Add("D", "FG");
dict.Add("E", "HI");
Console.WriteLine("Key/Value pairs...");
foreach(DictionaryEntry d in dict)
Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
}
}출력 결과
위 코드를 실행하면 다음과 같은 출력이 생성됩니다.
Key/Value pairs... Key = A, Value = AB Key = B, Value = BC Key = C, Value = DE Key = D, Value = FG Key = E, Value = HI
예제 2: 초기 크기 10으로 생성하기
이번에는 초기 크기 10을 지정하여 HybridDictionary를 생성하고, 10개의 키/값 쌍을 추가하는 예제를 살펴보겠습니다.
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main(){
HybridDictionary dict = new HybridDictionary(10);
dict.Add("1", 100);
dict.Add("2", 200);
dict.Add("3", 300);
dict.Add("4", 400);
dict.Add("5", 500);
dict.Add("6", 600);
dict.Add("7", 700);
dict.Add("8", 800);
dict.Add("9", 900);
dict.Add("10", 1000);
Console.WriteLine("Key/Value pairs...");
foreach(DictionaryEntry d in dict)
Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
}
}출력 결과
위 코드를 실행하면 다음과 같은 출력이 생성됩니다.
Key/Value pairs... Key = 10, Value = 1000 Key = 1, Value = 100 Key = 2, Value = 200 Key = 3, Value = 300 Key = 4, Value = 400 Key = 5, Value = 500 Key = 6, Value = 600 Key = 7, Value = 700 Key = 8, Value = 800 Key = 9, Value = 900
정리
HybridDictionary 생성자에 초기 크기를 지정하면 요소 개수를 미리 파악할 수 있는 경우 불필요한 재할당을 줄여 성능을 향상시킬 수 있습니다. 위 예제처럼 new HybridDictionary(size) 형태로 간단하게 사용할 수 있습니다.