What's the performance hit of List.OfType<> where the entire list is that type?
I have an architecture where we are passing our data nodes as IE开发者_如何转开发numerable<BaseNode>
. It all works great, but in each subclass we want to store these as List<AnotherNode>
as everything in that class creates and uses AnotherNode
objects (we have about 15 different subclasses).
The one place using the more strongly typed list doesn't work is the root classes method that returns a type IEnumerable<BaseNode>
and with the covariance limitations in .net 3.5, that can't be returned. (We have to stay on .net 3.5 for now.)
But if I have List<AnotherNode> data;
and return data.OfType<BaseNode>();
- that works fine. So here's my question.
As all of data is of type BaseNode
- what's the performance hit of this call? Because the alternative is I have to cast in places which has a small performance hit - but it's also a situation where we give up everything knowing it's type.
Two minor things:
There is a small, but measurable overhead associated with yielding each item in the enumerator. If you need to care about this because you're in a very tight inner loop, you're actually better off iterating with a for loop on the list directly. Most likely this doesn't matter.
Because the result is
IEnumerable<BaseNode>
and has already been filtered through a yielding enumeration function, subsequent calls to methods like Count() or ElementAt() will not take advantage of optimizations in the LINQ implementation for Lists. This is also unlikely to be a problem unless you make frequent use of these extension methods and have a very large number of elements.
Have you seen the Cast<T>()
Linq operator? It should be more performant than OfType<T>()
.
Basically there is a condition that is run with OfType<T>()
if (item is T) {
yield return (T)item;
}
Contrast that with what Cast<T>()
does:
yield return (T)item;
精彩评论