C#中Array和List的效能比較
阿新 • • 發佈:2020-09-09
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; string[] array = new string[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.ToString(); } 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(); } } }
作者:艾孜爾江