当使用扩展方法时IEnumerable<T>
Count() http://msdn.microsoft.com/en-us/library/bb535181.aspx,数组至少比列表慢两倍。
Function Count()
List<int> 2,299
int[] 6,903
差异从何而来?
据我所知,两者都在调用Count
的财产ICollection
:
如果源的类型实现了 ICollection,则该实现用于获取元素的计数。否则,此方法确定计数。
对于它返回的列表List<T>.Count http://msdn.microsoft.com/en-us/library/27b47ht3.aspx,对于数组,Array.Length
。而且,Array.Length
应该比List<T>.Count
.
基准:
class Program
{
public const long Iterations = (long)1e8;
static void Main()
{
var list = new List<int>(){1};
var array = new int[1];
array[0] = 1;
var results = new Dictionary<string, TimeSpan>();
results.Add("List<int>", Benchmark(list, Iterations));
results.Add("int[]", Benchmark(array, Iterations));
Console.WriteLine("Function".PadRight(30) + "Count()");
foreach (var result in results)
{
Console.WriteLine("{0}{1}", result.Key.PadRight(30), Math.Round(result.Value.TotalSeconds, 3));
}
Console.ReadLine();
}
public static TimeSpan Benchmark(IEnumerable<int> source, long iterations)
{
var countWatch = new Stopwatch();
countWatch.Start();
for (long i = 0; i < iterations; i++) source.Count();
countWatch.Stop();
return countWatch.Elapsed;
}
}
Edit:
leppie https://stackoverflow.com/a/16209739/128662 and Knaģis https://stackoverflow.com/a/16209469/128662答案非常惊人,但我想补充一点。
正如乔恩·斯基特所说: http://msmvps.com/blogs/jon_skeet/archive/2010/12/26/reimplementing-linq-to-objects-part-7-count-and-longcount.aspx
实际上有两个等效的块,只是测试
不同的集合接口类型,并使用它找到的任何一种
首先(如果有的话)。我不知道 .NET 实现是否测试
ICollection 或 ICollection 首先 - 我可以通过实现来测试它
当然,两个接口都返回不同的计数,
但这可能有点过分了。这并不重要
除了轻微的性能差异外,集合表现良好
- 我们想首先测试“最有可能”的界面,我认为这是通用的。
通用的可能是最有可能发生的,但如果将两者颠倒,即在通用的转换之前调用非通用的转换,Array.Count() 会比 List.Count() 快一点。另一方面,非通用版本对于 List 来说速度较慢。
很高兴知道是否有人想打电话Count()
在 1e8 迭代循环中!
Function ICollection<T> Cast ICollection Cast
List 1,268 1,738
Array 5,925 1,683