I have a query that's running slow (in a loop of about 100 it takes 5-10 seconds) and have no clue why. It's simply querying against a List of objects... your help is much appreciated!
I'm basically querying for Schedules that have been assigned to specific managers. It must be from the specified Shifts week OR the first 2 days of next week OR the last 2 days of the previous week.
I tried calculating .AddDays before 开发者_运维知识库but that didn't help. When I ran a performance test it highlighted the "from" statement below.
List<Schedule> _schedule = Schedule.GetAll();
List<Shift> _shifts = Shift.GetAll();
// Then later...
List<Schedule> filteredSchedule = (from sch in _schedule
from s in _shifts
where
**sch.ShiftID == s.ShiftID
& (sch.ManagerID == 1 | sch.ManagerID == 2 | sch.ManagerID == 3)
& ((s.ScheduleWeek == shift.ScheduleWeek)
| (s.ScheduleWeek == shift.ScheduleWeek.AddDays(7)
& (s.DayOfWeek == 1 | s.Code == 2))
| (sch.ScheduleWeek == shift.ScheduleWeek.AddDays(-7)
& (s.DayOfWeek == 5 | s.Code == 6)))**
select sch)
.OrderBy(sch => sch.ScheduleWeek)
.ThenBy(sch => sch.DayOfWeek)
.ToList();
First port of call: use &&
instead of &
and ||
instead of |
. Otherwise all the subexpressions in the where
clause will be evaluated, even if the answer is already known.
Second port of call: use a join instead of two "from" clauses with a where:
var filteredSchedule = (from sch in _schedule
join s in _shifts on s.ShiftID equals sch.ShiftID
where ... rest of the condition ...
Basically that's going to create a hash of all the shift IDs, so it can quickly look up possible matches for each schedule.
精彩评论