views:

51

answers:

2

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:

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?

+1  A: 

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. 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().

var results = 
    (from a in Table
     group a by a.Value into b
     select new {Group = b}).ToList();
Mark Byers
But would that make it (the whole of the posted code) any faster?
Henk Holterman
I doubt it, but to be sure you should measure. What it will do though is take the execution cost up-front so that the iteration is faster. It seems to me that the OP's concern was more that the iteration was surprisingly slow rather than the total runtime of the code being slow. If you're not sure what is going on behind the scenes then you might expect the first line to be the slow one and the loop to be fast.
Mark Byers
A: 

If you're using .NET 4, have a look at P-LINQ or Parallel ForEach loops. That should dramatically increase performance.

Can't really tell based on the info given, but it may be a SQL query taking too long?

If it's the ForEach loop that's really causing the bottleneck, then the Parallel ForEach will be your best bet.

Steve Danner
If it's I/O bound (database) a few extra threads won't help much. I think it depends (on unavailable details).
Henk Holterman
That will only have a potential improvement for LINQ to Objects, but if this is using an IQueryable<T>, it won't help (much), since the bottleneck is probably in the backend.
Reed Copsey
@Reed, yeah it's like Henk said, it's based completely on unavailable details. If the Calcs being done in the foreach loop are the issue, this would help, or even if the LINQ statement is against an object collection, but we don't know from the info given.
Steve Danner