天天看點

C#中Array和List的性能比較

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace TestListArrayPerformance
{
    class Program
    {
        static void Main(string[] args)
        {
            //const int COUNT = 1000;
            const int COUNT = 10000000;
            
            //Test string's performance
            //string[] array = new string[COUNT]; // Volumn is predefined
            //Test integers' performance
            int[] array = new int[COUNT]; // Volumn is predefined

            //Test string's performance
            //List<string> list = new List<string>(); // Volumn is changable
            //Test integers' performance
            List<int> list = new List<int>(); // Volumn is changable
            
            Console.WriteLine("The count of the elements is: {0}. \n", COUNT);

            Console.Write("Total time cost for an Array initialization is: ");
            
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();

            for (int i = 0; i < COUNT; i++)
            {
                //Test string's performance
                //array[i] = i.ToString();

                //Test integers' performance
                array[i] = i;
            }


            stopWatch.Stop();
            Console.Write(stopWatch.ElapsedMilliseconds.ToString() + "ms.");

            stopWatch.Reset();
            stopWatch.Start();
            Console.WriteLine("\n");

            for (int i = 0; i < COUNT; i++)
            {
                //Test string's performance
                //list.Add(i.ToString());

                //Test integers' performance
                list.Add(i);
            }

            stopWatch.Stop();
            Console.Write("Total time cost for a List initialization is: ");
            Console.Write(stopWatch.ElapsedMilliseconds.ToString() + "ms.");
            stopWatch.Reset();

            Console.ReadKey();
        }
    }
}      

結論

  1. 在資料量龐大的時候List的性能比Array的性能低;
  2. 在資料量較小的時候List的性能和Array的性能基本上差不多;
  3. 在資料量小或者長度不可知的情況下推薦使用List,因為其長度是可變的;
  4. 在資料量大或者資料量的長度明确的情況下推薦使用Array,因為這樣可以提高性能。

相關連結

​​List源碼​​

​​Array源碼​​