Ale*_*kiy 4 .net c# linq performance
问题是:为什么它使用这个代码
if (source is TSource[])
return (IEnumerable<TResult>) new Enumerable.WhereSelectArrayIterator<TSource, TResult>((TSource[]) source, (Func<TSource, bool>) null, selector);
if (source is List<TSource>)
return (IEnumerable<TResult>) new Enumerable.WhereSelectListIterator<TSource, TResult>((List<TSource>) source, (Func<TSource, bool>) null, selector);
else
return (IEnumerable<TResult>) new Enumerable.WhereSelectEnumerableIterator<TSource, TResult>(source, (Func<TSource, bool>) null, selector);
}
Run Code Online (Sandbox Code Playgroud)
代替
if (source is IList<TSource>)
return (IEnumerable<TResult>) new Enumerable.WhereSelectIListIterator<TSource, TResult>((List<TSource>) source, (Func<TSource, bool>) null, selector);
return (IEnumerable<TResult>) new Enumerable.WhereSelectEnumerableIterator<TSource, TResult>(source, (Func<TSource, bool>) null, selector);
}
Run Code Online (Sandbox Code Playgroud)
我的意思是List<T>和T[]这两个工具IList<T>,他们都具有索引和工具IEnumerable<T>,所以他们都可以在同一个奇异的方式进行迭代,但现在使用不同的迭代器.
它只是一个优化,涵盖了过滤数组或列表的极其常见的情况.
WhereSelectArrayIterator不使用数组的基础枚举器 - 它使用索引器.从性能的角度来看,最好直接使用数组索引器,而不是通过IList<T>索引器或使用枚举器.
WhereSelectListIterator确实使用列表的枚举器,但因为它"知道" List<TSource>枚举器的类型是结构 List<TSource>.Enumerator(它可以使用List<TSource>与接口方法分开的特殊GetEnumerator方法检索),它避免了将枚举器装入堆中- 如果你使用的话,你必须要做的IEnumerator<TSource>.
WhereSelectEnumerableIterator是使用IEnumerator<TSource>源代码支持的一般情况- 它适用于所有类型的序列,但没有任何特殊的优化.如果枚举器恰好是一个结构,那么运气很难 - 它将被装箱.