天天看點

泛型集合List<T>和非泛型集合ArrayList性能比較

使用ArrayList 這樣的非泛型集合過程中,要進行裝箱拆箱的操作,會有較大性能的損失

而 List<T> 泛型集合就沒有這樣的問題

ArrayList的add方法的參數是Object類型

當我們把參數傳入時會進行裝箱操作,将參數轉換成Object類型

示例:

  1. DateTime startTime = new DateTime();

  2. DateTime endTime = new DateTime();

  3. //------------------ArrayList ------------------

  4. ArrayList list = new ArrayList();

  5. startTime = DateTime.Now;

  6. //裝箱操作

  7. for (int i = 0; i < 1000000; i++)

  8. {

  9. list.Add(i);

  10. }

  11. int iCount = 0;

  12. //拆箱操作

  13. foreach (int i in list)

  14. {

  15. iCount += 1;

  16. }

  17. Console.WriteLine("輸出結果 :{0}", iCount.ToString());

  18. endTime = DateTime.Now;

  19. TimeSpan ts = endTime - startTime;

  20. Console.WriteLine("使用ArrayList的結果:{1}" , ts.TotalMilliseconds);

  21. //---------------------List<int>---------------

  22. List<int> list2 = new List<int>();

  23. startTime = DateTime.Now;

  24. for (int i = 0; i < 1000000; i++)

  25. {

  26. list2.Add(i);

  27. }

  28. iCount = 0;

  29. foreach (int i in list2)

  30. {

  31. iCount += 1;

  32. }

  33. Console.WriteLine("輸出結果 :{0}", iCount.ToString());

  34. endTime = DateTime.Now;

  35. ts = endTime - startTime;

  36. Console.WriteLine("使用ArrayList的結果:{1}" , ts.TotalMilliseconds);

  37. Console.Read();

結果:

    使用 ArrayList 耗時:92s

    使用 List<T>耗時:25s