使用ArrayList 這樣的非泛型集合過程中,要進行裝箱拆箱的操作,會有較大性能的損失
而 List<T> 泛型集合就沒有這樣的問題
ArrayList的add方法的參數是Object類型
當我們把參數傳入時會進行裝箱操作,将參數轉換成Object類型
示例:
-
DateTime startTime = new DateTime();
-
DateTime endTime = new DateTime();
-
//------------------ArrayList ------------------
-
ArrayList list = new ArrayList();
-
startTime = DateTime.Now;
-
//裝箱操作
-
for (int i = 0; i < 1000000; i++)
-
{
-
list.Add(i);
-
}
-
int iCount = 0;
-
//拆箱操作
-
foreach (int i in list)
-
{
-
iCount += 1;
-
}
-
Console.WriteLine("輸出結果 :{0}", iCount.ToString());
-
endTime = DateTime.Now;
-
TimeSpan ts = endTime - startTime;
-
Console.WriteLine("使用ArrayList的結果:{1}" , ts.TotalMilliseconds);
-
//---------------------List<int>---------------
-
List<int> list2 = new List<int>();
-
startTime = DateTime.Now;
-
for (int i = 0; i < 1000000; i++)
-
{
-
list2.Add(i);
-
}
-
iCount = 0;
-
foreach (int i in list2)
-
{
-
iCount += 1;
-
}
-
Console.WriteLine("輸出結果 :{0}", iCount.ToString());
-
endTime = DateTime.Now;
-
ts = endTime - startTime;
-
Console.WriteLine("使用ArrayList的結果:{1}" , ts.TotalMilliseconds);
-
Console.Read();
結果:
使用 ArrayList 耗時:92s
使用 List<T>耗時:25s