【发布时间】:2018-09-09 23:22:47
【问题描述】:
假设我有一个 IEnnumerable<Thing> enumerable 对象,并且此列表中的每个 Thing 生成起来都很昂贵。
当我去执行下面的代码时,当代码到达第 1 行时会有相当大的开销,因为据我了解,整个列表是在开始迭代之前生成的。
foreach(Thing t in enumerable) // line 1
{ // line 2
DoStuffWith(t); // line 3
}
有没有办法只根据需要生成每个Thing?像这样
while(enumerable.HasMoreThings())
{
var e = enumerable.GenerateNextThing();
DoStuffWith(e);
}
原码
using (var db = new PolyPrintEntities())
{
var sw = new Stopwatch();
sw.Start();
IEnumerable<NotificationDto> notifications = db.EmailServiceNotifications
.Select(not => new NotificationDto
{
Notification_ID = not.Notification_ID,
StoredProcedure = not.StoredProcedure,
SubjectLine = not.SubjectLine,
BodyPreface = not.BodyPreface,
Frequency = not.Frequency,
TakesDateRange = not.TakesDateRange,
DateRangeIntervalHours = not.DateRangeIntervalHours,
TakesAssociateId = not.TakesAssociateId,
NotificationType = not.NotificationType,
Associates = not.SubscriptionEvent.SubscriptionSubscribers
.Select(ss => new AssociateDto
{
Record_Number = ss.Associate.Record_Number,
Name = ss.Associate.Name,
Email = ss.Associate.EMail
})
});
sw.Stop();
Console.WriteLine($"Enumeration:{sw.ElapsedMilliseconds}"); //about .5 seconds
sw.Reset();
sw.Start();
//List is generated here, this is where lag happens.
int i = 0;
foreach (var n in notifications)
{
if(i == 0)
{
sw.Stop();
Console.WriteLine($"Generation:{sw.ElapsedMilliseconds}"); //about 10 seconds
i++;
}
var ret = n.GetEmails();
db.EmailQueues.AddRange(ret);
}
db.SaveChanges();
}
【问题讨论】:
-
"整个列表在开始迭代之前就在那里生成。"这正是
IEnumerable/IEnumerable<T>接口所避免的。你搞错了 -
补充一下 Camilo 所说的,
while (enumerable.MoveNext())是当你迭代一个可枚举的对象时发生的事情。我们需要查看更多您的代码 - 问题一定出在其他地方。 (什么是创建列表?你在使用yield吗?) -
枚举来自于一个 Linq 语句,该语句通过实体框架减小对数据库的查询大小。我对创建 IEnumerable 的代码块和只创建第一个对象的 foreach 循环部分进行了计时。我已经修改了我的帖子以包含导致我写这个问题的代码
-
我们需要看到最重要的部分:
//List is generated here, this is where lag happens. -
@maccettura 好的。对此感到抱歉,我不确定公约是什么。但现在我知道了,谢谢你的建议。
标签: c# .net linq deferred-execution