Array.Count() VS Array.Length

  • 4809
  • 0
  • C#
  • 2013-07-05

摘要:Array.Count() VS Array.Length

某天,在跟同事閒聊時,發現他正在寫的程式中發現在判斷Array筆數時都使用Array.Count()來判斷,當下就跟他說明使用Array.Length 理論上會比Array.Count() 來得快,當下我同事也做出修正。那…這兩種方法到底實際上差多少? 我就來測試一下

測試程式

	    List collection = new List();
            for (int i = 0; i < 100000; i++)
            {
                Random rNumber = new Random();
                collection.Add(rNumber.Next(0, 100000));
            }
            int[] rs = collection.ToArray();
            int cal1, cal2;
            Stopwatch sw = new Stopwatch();

            sw.Start();
            cal1 = rs.Count();
            sw.Stop();
            Console.WriteLine(string.Format("Use Count() Method expend {0}ms", 
            sw.Elapsed.TotalMilliseconds ));

            sw.Reset();

            sw.Start();
            cal2 = rs.Length;
            sw.Stop();
            Console.WriteLine(string.Format("Use Length Property expend {0}ms",
              sw.Elapsed.TotalMilliseconds));
            Console.Read

測試結果