使用ArrayList:
static void Main(string[] args)
{
ArrayList arrList = new ArrayList();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 100000; i++)
{
arrList.Add(i);
}
sw.Stop();
Console.WriteLine(sw.Elapsed);
Console.ReadKey();
}
執行時間為:
將以上程式碼替換成List<int>
static void Main(string[] args)
{
//ArrayList arrList = new ArrayList();
List arrList = new List();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 100000; i++)
{
arrList.Add(i);
}
sw.Stop();
Console.WriteLine(sw.Elapsed);
Console.ReadKey();
}
執行時間為:
可以看到使用List<T> 的速度以這個case來說快了3倍左右
為什麼呢?
這是因為ArrayList 在add 方法時要傳入的值的型態為object
在此就發生了裝箱
何謂裝箱與拆箱?
Boxing(裝箱) 與 UnBoxing(拆箱) 的意義為
- 裝箱:將數值型態轉換為參考型態
- 拆箱:將參考型態轉換為數值型態

沒有留言:
張貼留言