C#学习教程:Array.Count()比List.Count()慢很多至少比列表慢两倍。FunctionCount()List2,299int[]6,903差异从何而来?我知道两者都在调用ICollection的Count属性:如果源的类型实现了ICollection,则该实现用于获取元素的计数。否则,此方法确定计数。对于列表,它返回List.Count,对于数组,它返回Array.Length。此外,Array.Length应短于List.Count。基准测试:类程序{publicconstlongIterations=(long)1e8;staticvoidMain(){varlist=newList(){1};vararray=newint[1];数组[0]=1;varresults=newDictionary();results.Add("List",Benchmark(list,Iterations));结果.Add("int[]",Benchmark(array,Iterations));Console.WriteLine("Function".PadRight(30)+"Count()");foreach(varresultinresults){Console.WriteLine("{0}{1}",result.Key.PadRight(30),Math.Round(result.Value.TotalSeconds,3));}控制台.ReadLine();}publicstaticTimeSpanBenchmark(IEnumerablesource,longiterations){varcountWatch=newStopwatch();countWatch.Start();for(longi=0;i
