Does the .Net Framework implementation of Linq optimize Skip for indexable types?
Here's an example:
static int Main(string[] args)
{
foreach(string arg in args.Skip(77))
{
Console.WriteLine(arg);
}
开发者_JAVA技巧 return 0;
}
Assuming enough args
, does this call MoveNext
77 times inside Skip
? Or does Skip
jump straight to the appropriate index?
Embarrassingly, I was wrong.
No.
public static IEnumerable<TSource> Skip<TSource>(this IEnumerable<TSource> source, int count) {
if (source == null) throw Error.ArgumentNull("source");
return SkipIterator<TSource>(source, count);
}
static IEnumerable<TSource> SkipIterator<TSource>(IEnumerable<TSource> source, int count) {
using (IEnumerator<TSource> e = source.GetEnumerator()) {
while (count > 0 && e.MoveNext()) count--;
if (count <= 0) {
while (e.MoveNext()) yield return e.Current;
}
}
}
Jon Skeet explains why it can't do that.
精彩评论