3

In linq-to-sql which example (if either) would we expect to be more efficient/faster to evaluate? Do they compile to the same sql? Are there any other factors that I should consider when choosing between these examples?

(with DbContext context)

context.Events
   .Where(evt => evt.Date <= endDate && evt.Date > startDate);

or...

context.Events
   .Where(evt => evt.Date <= endDate)
   .Where(evt => evt.Date > startDate);
Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
gingerbreadboy
  • 7,386
  • 5
  • 36
  • 62
  • 1
    The duplicate question link answers this perfectly, thanks. – gingerbreadboy Jan 19 '17 at 14:27
  • 3
    Ultimately those will both be translated to the same SQL, so there would be no real difference. – juharr Jan 19 '17 at 14:27
  • 1
    Interestingly someone opened it again and therefore rejected the duplicate even if OP says the opposite. So here are some related (or duplicates): http://stackoverflow.com/questions/23674778/linq-differences-between-single-where-with-multiple-conditions-and-consecutive or http://stackoverflow.com/questions/6359980/proper-linq-where-clauses?noredirect=1&lq=1 or http://stackoverflow.com/questions/664683/should-i-use-two-where-clauses-or-in-my-linq-query (misleading accepted) – Tim Schmelter Jan 19 '17 at 14:30
  • Possible duplicate of [Should I use two "where" clauses or "&&" in my LINQ query?](http://stackoverflow.com/questions/664683/should-i-use-two-where-clauses-or-in-my-linq-query) – Sнаđошƒаӽ Jan 19 '17 at 17:38

1 Answers1

1

As juharr stated above, both with generate exactly the same SQL query.

Just out of curiosity I did a time test on my own database and found && was considerably faster at generating the query.

            for (int i = 0; i < 500; i++)
            {
                var wko = db.WorkOrders
                    .Where(evt => DateTime.Now > evt.LastModified)
                    .Where(evt => DateTime.Now > evt.Opened);
            }
            for (int i = 0; i < 500; i++)
            {
                var wko2 = db.WorkOrders
                    .Where(evt => DateTime.Now > evt.LastModified && DateTime.Now > evt.Opened);
            }

The first loop completed in <= 24ms The second loop completed in <= 16ms

I'm sure this will usually have very little effect on your performance, but an FYI.