1. 程式人生 > >ArrayList與List效能測試

ArrayList與List效能測試

理論:由於ArrayList儲存資料存在裝箱(讀取資料存在拆箱),而泛型List<T>直接對T型別資料進行儲存,不存在裝箱與拆箱拆箱操作,理論上速度應該快一些。

廢話少說,上程式碼。

 1    public void Test2()
 2         {
 3             float testData = 0.01f;
 4             long length = 100000000;
 5             Stopwatch sw = new Stopwatch();
 6             sw.Start();
 7             ArrayList arrayList = new
ArrayList(); 8 for (long i = 0; i < length; i++) 9 { 10 arrayList.Add(testData); 11 } 12 sw.Stop(); 13 14 Stopwatch sw2 = new Stopwatch(); 15 sw2.Start(); 16 List<float> list = new List<float
>(); 17 for (int i = 0; i < length; i++) 18 { 19 list.Add(testData); 20 } 21 sw2.Stop(); 22 Console.WriteLine("{0}次ArrayList裝箱時間{1}", length, sw.Elapsed); 23 Console.WriteLine("{0}次List裝箱時間 {1}", length, sw2.Elapsed);
24 25 }

輸出結果ArrayList進行1億此裝箱操作耗時9秒多,而List<T>泛型直接儲存資料不到1秒,效能高下立見。