慢的foreach()在LINQ查询 - 了ToList()提高性能极大 - 这是为什么? [英] Slow foreach() on a LINQ query - ToList() boosts performance immensely - why is this?
问题描述
我有种把握整体延迟执行的概念,但下面有我不解...
在包含约1000行的DataTable,我称之为的 AsEnumerable()的。然后,我选择实体返回到强类型类的IEnumerable (1) ...这里就是我感到困惑:我在集合foreach循环;使用大量的其中()的通话从集合中的各个项目选择的东西(2) ...它死了缓慢。
-
DataTable.AsEnumerable()。选择(R = gt;新建ObjectRepresentation {...});
-
item.Where(I => i.SomeEnum == SomeEnum.Something)
......但是,如果我调用的了ToList()的右后我的 AsEnumerable()的DataTable中调用,foreach循环花费不到一秒钟内完成。
我缺少的是在这里吗?我是不是有效调用的 AsEnumerable()的每一次我循环遍历?或每一次我访问集合中的项目?或我每次做一次的其中()的在集合中的一个项目叫?或上述所有?
的更新
有点完整的代码:
公共类ObjectRepresentation
{
公共SomeEnum SomeEnum {搞定;组; }
}
变种集合= DataTable.AsEnumerable()选择(R =方式>新ObjectRepresentation
{
SomeEnum =(SomeEnum)转换.ToInt32(R [SomeEnum])
});
的foreach(在收集VAR项目)//慢环
{
// 10左右在哪里()这个循环
内的项目要求}
集合= collection.ToList(); //命中超高速按钮!
的foreach(在收集VAR项目)//快速环路
{
// 10左右在哪里()这个循环
内的项目要求}
它不会从数据库中获取的所有项目,直到你输入
了ToList或第一个或单身
在的foreach,您将查询发送到数据库中的每个项目。因此,它的工作原理慢。打开SQL事件探查器更好地理解。
I kind of grasp the whole delayed execution concept, but the following has me puzzled...
On a DataTable containing about 1000 rows, I call AsEnumerable(). I then select the entities returned into an IEnumerable of strongly typed classes (1)... Here's where I get confused: I do a foreach loop on the collection; selecting stuff from the individual items in the collection using a bunch of Where() calls (2) ... And it's dead slow.
DataTable.AsEnumerable().Select(r => new ObjectRepresentation { ... });
item.Where(i => i.SomeEnum == SomeEnum.Something)
... But if I call ToList() right after my AsEnumerable() call on the DataTable, the foreach loop takes less than a second to complete.
What am I missing here? Am I effectively calling AsEnumerable() each time my loop iterates? Or each time I access an item in the collection? Or each time I do a Where() call on an item in the collection? Or all the above?
Update
Somewhat complete code:
public class ObjectRepresentation
{
public SomeEnum SomeEnum { get; set; }
}
var collection = DataTable.AsEnumerable().Select(r => new ObjectRepresentation
{
SomeEnum = (SomeEnum)Convert.ToInt32(r["SomeEnum"])
});
foreach(var item in collection) // slow loop
{
// 10 or so Where() calls on item inside this loop
}
collection = collection.ToList(); // Hit hyper speed button!
foreach(var item in collection) // fast loop
{
// 10 or so Where() calls on item inside this loop
}
It will not get all items from database until you type
ToList or First or Single
In foreach, you send a query into database for each item. So it works slower. Open your sql profiler to understand better.
这篇关于慢的foreach()在LINQ查询 - 了ToList()提高性能极大 - 这是为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!