我提出了一个问题并得到了回答here https://stackoverflow.com/a/23606749/859154关于我遇到的性能问题large数据收集。 (使用 linq 创建)
好吧,我们先把它放在一边。
但其中一个有趣的(并且geniusly)优化 - Marc 建议 - 是Batchify
linq 查询。
/*1*/ static IEnumerable<T> Batchify<T>(this IEnumerable<T> source, int count)
/*2*/ {
/*3*/ var list = new List<T>(count);
/*4*/ foreach(var item in source)
/*5*/ {
/*6*/ list.Add(item);
/*7*/ if(list.Count == count)
/*8*/ {
/*9*/ foreach (var x in list) yield return x;
/*10*/ list.Clear();
/*11*/ }
/*12*/ }
/*13*/ foreach (var item in list) yield return item;
/*14*/ }
在这里,Batchify 的目的是确保我们不会帮助
服务器太多,每次操作之间花费相当长的时间 -
数据以1000为批次发明,每批次制作
很快就可以使用。
现在我明白了what它正在做,但我can't说出区别,因为我可能会错过它实际工作的方式。 (有时你认为你知道一些事情......直到......)
好的,回到基础知识:
AFAIK,Linq 的工作方式就像这个链 –:
所以,我们不能开始枚举till的结果select
in :
Where-->OrderBy-->Select
已经完成了。
所以基本上我是waiting for select
具有all正确的数据(after where
, 后orderby
), and 只有那时- 我的代码可以触及这些值。 (产生自select
)
但根据我对Marc回答的理解,这些之间似乎存在差距yields
它允许其他资源做某事...(?)
如果是这样,那么在每次迭代之间#4
, 行后#9
,CPU还有时间做别的事吗?
Question
nb
我已经知道了(例如)select
无非是:
public static IEnumerable<TResult> Select<TSource,TResult>
(this IEnumerable<TSource> source, Func<TSource,TResult> selector)
{
foreach (TSource element in source)
yield return selector (elem![enter image description here][3]ent);
}
但如果是这样,我的代码就无法触及它,直到所有值(之后where
, orderby
) 计算...
edit :
对于那些询问是否有区别的人:https://i.stack.imgur.com/19Ojw.jpg https://i.stack.imgur.com/19Ojw.jpg
2秒为1M项目。9秒为5M items.
(ignore the second line of time , (extra console.write line).)
![enter image description here](https://i.stack.imgur.com/19Ojw.jpg)
这是 5m 列表:https://i.stack.imgur.com/DflGR.jpg https://i.stack.imgur.com/DflGR.jpg(第一个是 withBatchify ,另一个不是)