简体   繁体   English

通过分组的linq结果进行学习非常缓慢,有什么提示吗?

[英]Foreaching through grouped linq results is incredibly slow, any tips?

I did some profiling on a program that I'm running and the thing that takes the longest time is getting the results from the linq query: 我对正在运行的程序进行了性能分析,而花费时间最长的事情是从linq查询中获取结果:

var Results = 
    from a in Table
    group a by a.Value into b
    select new {Group = b};

foreach(var Result in Results)
{
    //Do calcs
}

Any ideas on how I can speed this up? 关于如何加快速度的任何想法?

I think you are confusing the query object with the results of that query. 我认为您正在将查询对象与该查询的结果混淆。 Your first variable doesn't contain the results, it contains a query object. 您的第一个变量不包含结果,它包含一个查询对象。 At this point the query hasn't been executed. 此时,查询尚未执行。 The execution is delayed until you actually need the results, and in your example this is done when you iterate in the foreach loop. 执行被延迟,直到您真正需要结果为止,在您的示例中,当您在foreach循环中进行迭代时,该操作才完成。 This is why the first statement executes quickly but the iteration is slow. 这就是为什么第一条语句执行速度快但迭代速度慢的原因。

If you want to store the results of the query in results so that they are already calculated by the time you start the foreach loop then add a call to ToList(). 如果要在结果中存储查询results以便在开始foreach循环时已经计算出results ,则可以添加对ToList()的调用。

var results = 
    (from a in Table
     group a by a.Value into b
     select new {Group = b}).ToList();

If you're using .NET 4, have a look at P-LINQ or Parallel ForEach loops. 如果您使用的是.NET 4,请查看P-LINQParallel ForEach循环。 That should dramatically increase performance. 那应该大大提高性能。

Can't really tell based on the info given, but it may be a SQL query taking too long? 根据给出的信息无法真正分辨,但可能是SQL查询花费的时间太长?

If it's the ForEach loop that's really causing the bottleneck, then the Parallel ForEach will be your best bet. 如果真正导致瓶颈的是ForEach循环,那么并行ForEach将是您最好的选择。

I have had the same problem with only 2000 Sqlite records (indexed) used for an MSChart, apparently this is caused by the LINQ group statement querying all records. 我只有2000条用于MSChart的Sqlite记录(索引)有相同的问题,显然这是由查询所有记录的LINQ组语句引起的。

The only solution I found was to go back to native SQL and the chart rendered instantaneously rather than 2 seconds using LINQ with SQlite. 我发现的唯一解决方案是返回本机SQL,并使用LINQ和SQlite即时绘制图表,而不是2秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM