I need to get data from Sql Azure during inside one month.
There are 2 equal (for result) options:
Where
filter by month and year:
query = query.Where(a => a.Date.Year == dayOfMonth.Year && a.Date.Month == dayOfMonth.Month)
Where
filter from/till:
DateTime firstDayOfMonth = dayOfMonth.GetFirstDayOfMonth().Date; // returns 09/01/2022 00:00:00 for Sept 2022
DateTime lastDayOfMonth = dayOfMonth.GetLastDayOfMonth().ToEndOfTheDay(); // returns 09/30/2022 23:59:59 for Sept 2022
query = query.Where(a => a.Date >= firstDayOfMonth && a.Date <= lastDayOfMonth);
Which option is the better (by performance or other reasons) and why?
Thank you
CodePudding user response:
Performance Wise
First One is faster. Suppose you have 100 records then
High level time complexity would be
First Query
time Complexity = time to traverse 100 records and compare day, month and year.
TC approx= O(100);
'Second Query'
time Complexity = operation of getting first day operation of getting last day time to traverse 100 records and compare date greater or equal to first and less or equal to last day although in this case also it compare day, month and year because internally it is doing same thing (comparing day, month and year).
TC approx= O(1) O(1) O(100)
TC approx= O(102)
Though difference in execution is very minor.
Readability
In this point of view, Second one is more readable and understandable.
As per my point of view, In coding, performance matter more than readability. for understandability or Readability , can write comments in code. So I will go with first one