user2299182
user2299182

Reputation: 109

Please help me optimizing this Linq statement

Can help me to optimize the following LINQ statement. I'm using NHibernate as ORM. This statement is taking more than a minute to execute. It shouldn't take that much time.

 var inValidIntroductionDates = environment.IntroductionDateInfo.IntroductionDateDetails
                                .OrderByDescending(x => x.ApplicationDate)
                                .Where(x => x.VaccineDetail.Id == vaccine.Id &&
                                            x.ViewInfo.Id == viewInfoDetail.ViewInfo.Id &&
                                            x.MasterForecastInfo.Id == scenarioId &&
                                            x.IsIntroductionDateValid == false)
                                .ToList();

Thanks

Upvotes: 0

Views: 68

Answers (3)

MoCapitan
MoCapitan

Reputation: 449

Some things to consider:

  • Please attach a profiler to your database and tell us how the exact statement that is sent to the database
  • Find out if the statement is executed slow or if nHibernate processing takes the time
  • if it is the database query: optimize for the statement (e.g. index, execution plan,...)
  • if too many queries are executed: combat the n+1
  • if it is nHibernate execution: Turn off nHibernate logging

Please let us know what's the point.

Regards, Michael

Upvotes: 1

Georgi-it
Georgi-it

Reputation: 3686

var inValidIntroductionDates = environment.IntroductionDateInfo.IntroductionDateDetails.Where(
                        x => x.VaccineDetail.Id == vaccine.Id && x.ViewInfo.Id == viewInfoDetail.ViewInfo.Id && x.MasterForecastInfo.Id == scenarioId && x.IsIntroductionDateValid == false).OrderByDescending(x => x.ApplicationDate).ToList();

first find, then order

Upvotes: 1

Habib
Habib

Reputation: 223267

Move the Where clause before OrderByDescending to reduce the number of records participating in the order by statement. Like

var inValidIntroductionDates = environment.IntroductionDateInfo.IntroductionDateDetails
                               .Where( x => x.VaccineDetail.Id == vaccine.Id && 
                                     x.ViewInfo.Id == viewInfoDetail.ViewInfo.Id && 
                                     x.MasterForecastInfo.Id == scenarioId && 
                                     x.IsIntroductionDateValid == false)
                                .OrderByDescending(x => x.ApplicationDate)
                                .ToList();

Also you can change

 x.IsIntroductionDateValid == false

to

 !x.IsIntroductionDateValid 

But that would not improve the performance. Just a readiblity option.

Upvotes: 1

Related Questions