A while ago I wrote an IList
extension method to enumerate across part of a list by using the indices. While refactoring I realized a similar query could be performed by calling Skip(toSkip).Take(amount)
. While benchmarking this I noticed that Skip
isn't optimized for IList
. With a bit of googling I ended up at a Jon Skeet post, discussing why optimizing methods like Skip
is dangerous.
As far as I understand the article, the problem is no exception is thrown in the optimized methods when the collection is modified, but as a comment states the msdn documentation conflicts itself.
If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or Reset throws an InvalidOperationException.
In IEnumerator.GetEnumerator():
If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.
I see merit in both conventions, and am a bit lost whether or not to optimize. What is a proper solution? I've been considering an IList.AssumeImmutable()
approach along the lines of AsParallel()
as mentioned by Kris Vandermotten in the comments. Does any implementation already exist, or is it a bad idea?