简体   繁体   中英

How to increase performance of foreach loop

I'm using a foreach loop to calculate answers against question.

It calculates all the answers against a question but when it loads the next question it takes one minute every time. How can I reduce this time?

List<Questionnaire> myQuestionnaires = report.Project
                                             .Questionnaires
                                             .Where(q => q.Active)
                                             .ToList<Questionnaire>();          

foreach (Questionnaire q in myQuestionnaires)
{
    foreach (ItemAnswer a in q.Answers)
    {
        //possible answers 
    }
}                

What I would do is not use .ToList() or .AsEnumerable(). Those two functions will execute the T-SQL being generated by your linq statements and pull all the records into memory.

The better alternative is to continue to use linq to filter your results with a predicate.

var query = report.Project
                  .Questionnaires
                  .Where(q => q.Active && q.Answers == /*some condition*/)

or

var query = report.Project
                  .Questionnaires
                  .Where(q => q.Active)
                  .Select(q => q.Answers) // Select the answers only
                  .Where(answers => answers.Property == /* some condition */)

Then once you have finished filtering your records, call .ToList() or .AsEnumerable() when read to fetch the results.

This enables you to use the database to do all the work instead of pulling the collection into memory and iterating.

It seems the issue of lazy loading,because LINQ have lazy loading enable by default. in your code part it will load all the Answers(without any join) from db for every question.

you can control Lazy Loading on data context level by using

    report.DeferredLoadingEnabled=false;

now you have to write some extra line of code for getting the answers,because now "q.Answers" will not be having data.You can write another Linq for getting the answer in first foreach loop,and it won't take that much time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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