Optimize LINQ for IList

点点圈 提交于 2019-11-30 18:59:38

I agree with Rafe that the undefined behavior is more correct. Only versioned collections can throw exceptions and not all collections are versioned (arrays being the largest example). Even versioned collections might misbehave if you make exactly 2^32 changes between calls to MoveNext.

Assuming you really care about the versioning behavior, the solution is to get an Enumerator for the IList and call MoveNext on it for every iteration:

    public static IEnumerable<T> Skip<T>(this IList<T> source, int count)
    {
        using (var e = source.GetEnumerator())
            while (count < source.Count && e.MoveNext())
                yield return source[count++];
    }

This way you get O(1) behavior by indexing, but you still get all the exception throwing behavior of calling MoveNext. Note that we only call MoveNext for the exception side-effects; we ignore the values that it's enumerating over.

The ReadOnlyCollection class might help with your immutable collection.

My advice: I personally would not try to "trick" the compiler unless you are having a performance issue. You never know, the next version could make your optimized code run twice as slow as the original. Don't preemptively optimize. The methods provided in the framework can produce some really optimized code that would be difficult to re-implement.

here is an article from msdn that gives info on what collections to use for different purposes. I would use an appropriate collection for the task instead of trying to optimize Skip and Take.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!