List<string> list = new List<string>() {"a", "b", "c"};
IEnumerable<string> enumerable = list;
int c1 = list.Count;
int c2 = list.Count();
int c3 = enumerable.Count();
Are there differences in performance and implementation between these last 3 statements? Will list.Count()
perform worse or the same as list.Count
, and does it matter if the reference is of type IEnumerable<string>
?
Let's look with Reflector:
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection<TSource> is2 = source as ICollection<TSource>;
if (is2 != null)
{
return is2.Count;
}
ICollection is3 = source as ICollection;
if (is3 != null)
{
return is3.Count;
}
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}
So, if your IEnumerable<T>
implements ICollection<T>
or ICollection
, it will return the Count
property.
The Linq Count method is clever enough not to iterate over the underlying collection if it implements ICollection interface and therefore already has Count property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With