Framework
Different with ArrayList, List<T> - Boxing, None Boxing(샘플 소스)
하얀전쟁^^
2009. 11. 25. 11:53
ArrayList는 값을 object형식으로 방식해서 받게 되어 모든 타입을 담을 수 있다.
하지만 Boxing이 일어나는데 이러한 빈번한 Boxing을 막기 위해 우리는 Generic에 있는 List<type>을 이용한다.
다음은 Boxing처리되는 ArrayList와 Boxing되지 않는 Generic List<>의 비교를 보도록 한다.
using System; using System.Collections; using System.Collections.Generic; namespace ConsoleApplication1 { struct RGB { public int red; public int green; public int blue; public RGB(int red, int green, int blue) { this.red = red; this.green = green; this.blue = blue; } public override string ToString() { return red.ToString("X") + green.ToString("X") + blue.ToString("X"); } } class Program { static ArrayList boxValue; static ListnoBoxValue; static void Main(string[] args) { DateTime start; DateTime middle; TimeSpan end; RGB rgb = new RGB(255, 255, 255); #region None Boxing Console.WriteLine("No Boxing : List .Add(RGB)"); noBoxValue = new List (); start = DateTime.Now; for (int i = 0; i < 10000000; i++) noBoxValue.Add(rgb); foreach (RGB value in noBoxValue) { string str = value.ToString(); } middle = DateTime.Now; end = middle - start; Console.WriteLine("시작 = {0}, 끝 = {1}, 경과시간 = {2}", start.ToString("hh:mm:ss"), middle.ToString("hh:mm:ss"), end.ToString()); #endregion #region Boxing Console.WriteLine("Boxing : ArrayList.Add(object)"); boxValue = new ArrayList(); start = DateTime.Now; for (int i = 0; i < 10000000; i++) boxValue.Add(rgb); foreach (RGB value in boxValue) { string str = value.ToString(); } middle = DateTime.Now; end = middle - start; Console.WriteLine("시작 = {0}, 끝 = {1}, 경과시간 = {2}", start.ToString("hh:mm:ss"), middle.ToString("hh:mm:ss"), end.ToString()); #endregion Console.Read(); } } }