Hel*_*rld 2 c# linq performance
我写了我的Where()实现:
public static IEnumerable<TSource> MyWhere<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
using (var enumerator = source.GetEnumerator())
{
if (!enumerator.MoveNext()) throw new InvalidOperationException("Sequence contains no elements");
do
{
var candidate = enumerator.Current;
if (predicate(candidate))
yield return candidate;
}
while (enumerator.MoveNext());
}
}
Run Code Online (Sandbox Code Playgroud)
并将其性能与LINQ进行比较Where():
var data = new int[1000000];
for (int i = 0; i < data.Length; i++)
data[i] = int.MaxValue;
Stopwatch stopwatch = new Stopwatch();
// My Where() test
stopwatch.Start();
var res2 = data.MyWhere(x => x == int.MaxValue).ToList();
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedTicks);
stopwatch.Reset();
// LINQ Where() test
stopwatch.Start();
var res = data.Where(x => x == int.MaxValue).ToList();
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedTicks);
Run Code Online (Sandbox Code Playgroud)
得到以下结果:
124487
50827
Run Code Online (Sandbox Code Playgroud)
帮助我理解,为什么MyWhere()实施太慢?我究竟做错了什么?谢谢.
Mat*_*zer 14
在检查参考源时判断您的顾虑 WhereArrayIterator
迭代器专门用于某些具体类型,如类型化数组,List<T>并且在访问某些给定IEnumerable<T>元素时会对效率产生积极影响.
例如,请参阅以下部分Enumerable.Where:
if (source is Iterator<TSource>) return ((Iterator<TSource>)source).Where(predicate);
if (source is TSource[]) return new WhereArrayIterator<TSource>((TSource[])source, predicate);
if (source is List<TSource>) return new WhereListIterator<TSource>((List<TSource>)source, predicate);
return new WhereEnumerableIterator<TSource>(source, predicate);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
162 次 |
| 最近记录: |