C# List<T> vs IEnumerable<T> performance question
c#, ienumerable, list, performance
Solution
In this particular case, using the `IEnumerable<T>` form will be more efficient, because you only need to know the count. There's no point in storing the data, resizing buffers etc if you don't need to.
If you needed to use the results again for any reason, the `List<T>` form would be more efficient.
Note that both the `Count()` extension method and the `Count` property will be efficient for `List<T>` as the implementation of `Count()` checks to see if the target sequence implements `ICollection<T>` and uses the `Count` property if so.
Another option which should be even more efficient (though only just) would be to call the overload of `Count` which takes a delegate:
private int GetProviderCount(Type type)
{
return _objectProviders.Count(provider =>
(provider.Key.IsAssignableFrom(type)
|| type.IsAssignableFrom(provider.Key))
&& provider.Value.SupportsType(type));
}
That will avoid the extra level of indirections incurred by the `Where` and `Select` clauses.
(As Marc says, for small amounts of data the performance differences will probably be negligible anyway.)
Problem
Hi suppose these 2 methods: ``` private List<IObjectProvider> GetProviderForType(Type type) { List<IObjectProvider> returnValue = new List<IObjectProvider>(); foreach (KeyValuePair<Type, IObjectProvider> provider in _objectProviders) { if ((provider.Key.IsAssignableFrom(type) || type.IsAssignableFrom(provider.Key)) && provider.Value.SupportsType(type)) { returnValue.Add(provider.Value); } } return returnValue; } private IEnumerable<IObjectProvider> GetProviderForType1(Type type) { foreach (KeyValuePair<Type, IObjectProvider> provider in _objectProviders) if ((provider.Key.IsAssignableFrom(type) || type.IsAssignableFrom(provider.Key)) && provider.Value.SupportsType(type)) yield return provider.Value; } ``` Which one is quicker? When I look at the first method, I see that the memory is allocated for List, what in my opinion it's not needed. The IEnumerable method seems to be quicker to me. For instance, suppose you call ``` int a = GetProviderForType(myType).Count; int b = GetProviderForType1(myType).Count(); ``` Now, another issue is, is there a performance difference between these 2 above? What do you think?