Some years back, somebody complained about the implementation of Linq.Reverse() and Microsoft promised to fix that. This was in 2008, so the question is, does Framework 4 have an optimized implementation of Linq.Reverse() that does not materialize the collection (i.e. copy all elements to an internal array) when the collection type allows it (e.g. IList<T>)?
Some years back, somebody complained about the implementation of Linq.Reverse() and Microsoft promised to
Share
Obviously it’s not possible to optimize all cases. If some object implements only
IEnumerable<T>and notIList<T>, you have to iterate it until the end to find the last element. So the optimization would be only for types that implementIList<T>(likeT[]orList<T>).Now, is it actually optimized in .Net 4.5 DP? Let’s fire up
ReflectorILSpy:Okay, how does
ReverseIterator<TSource>()look?What that iterator block does is to create a
Buffer<T>for the collection and iterate backwards through that. We’re almost there, what’sBuffer<T>?What have we here? We copy the content to an array. In every case. The only optimization is that if we know
Count(that is, the collection implementsICollection<T>), we don’t have to reallocate the array.So, the optimization for
IList<T>is not in .Net 4.5 DP. It creates a copy of the whole collection in every case.If I were to guess why it isn’t optimized, after reading Jon Skeet’s article on this issue, I think it’s because that optimization is observable. If you mutate the collection while iterating, you would see the changed data with the optimization, but the old data without it. And optimizations that actually change behavior of something in subtle ways are a bad thing, because of backwards compatibility.