Count()
メソッドは型に最適化されているICollection<T>
ため、パターンGetEnumerator()/MoveNext()/Dispose()
は使用されません。
list.Count();
に翻訳されます
((ICollection)list).Count;
一方、Any()
列挙子を構築する必要があります。したがって、このCount()
方法はより高速です。
IEnumerable
ここでは、4 つの異なるインスタンスのベンチマークを示します。のMyEmpty
ように見えますIEnumerable<T> MyEmpty<T>() { yield break; }
iterations : 100000000
Function Any() Count()
new List<int>() 4.310 2.252
Enumerable.Empty<int>() 3.623 6.975
new int[0] 3.960 7.036
MyEmpty<int>() 5.631 7.194
casperOneがコメントで言ったように、それEnumerable.Empty<int>() is ICollection<int>
は配列であり、へのキャストが自明ではないCount()
ため、配列は拡張機能には適していません。ICollection<int>
とにかく、自作の emptyについては、 が であるかどうかをテストするオーバーヘッドのために、よりも遅いとIEnumerable
予想したことがわかります。Count()
Any()
IEnumerable
ICollection
完全なベンチマーク:
class Program
{
public const long Iterations = (long)1e8;
static void Main()
{
var results = new Dictionary<string, Tuple<TimeSpan, TimeSpan>>();
results.Add("new List<int>()", Benchmark(new List<int>(), Iterations));
results.Add("Enumerable.Empty<int>()", Benchmark(Enumerable.Empty<int>(), Iterations));
results.Add("new int[0]", Benchmark(new int[0], Iterations));
results.Add("MyEmpty<int>()", Benchmark(MyEmpty<int>(), Iterations));
Console.WriteLine("Function".PadRight(30) + "Any()".PadRight(10) + "Count()");
foreach (var result in results)
{
Console.WriteLine("{0}{1}{2}", result.Key.PadRight(30), Math.Round(result.Value.Item1.TotalSeconds, 3).ToString().PadRight(10), Math.Round(result.Value.Item2.TotalSeconds, 3));
}
Console.ReadLine();
}
public static Tuple<TimeSpan, TimeSpan> Benchmark(IEnumerable<int> source, long iterations)
{
var anyWatch = new Stopwatch();
anyWatch.Start();
for (long i = 0; i < iterations; i++) source.Any();
anyWatch.Stop();
var countWatch = new Stopwatch();
countWatch.Start();
for (long i = 0; i < iterations; i++) source.Count();
countWatch.Stop();
return new Tuple<TimeSpan, TimeSpan>(anyWatch.Elapsed, countWatch.Elapsed);
}
public static IEnumerable<T> MyEmpty<T>() { yield break; }
}