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源碼




作者:艾孜爾江


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM