-1

My question is if there is any difference in speed between this query

query.Where(i => (i.FirstName.Contains(firstname) || string.IsNullOrEmpty(firstname)) &&
                                (i.LastName.Contains(secondname) || string.IsNullOrEmpty(secondname)) &&
                                (i.DateOfOrder == date || date == default(DateTime)));

and this code:

        if (!String.IsNullOrEmpty(firstname))
        {
            query = query.Where(i => i.FirstName.Contains(firstname));
        }

        if (!String.IsNullOrEmpty(secondname))
        {
            query = query.Where(i => i.FirstName.Contains(firstname));
        }

        if (date!=default(DateTime))
        {
            query = query.Where(i => i.DateOfOrder==date);
        }

Edited, thanks for the answers.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    Have you considered trying it to see if there is? – PaulF Jan 05 '17 at 09:15
  • Is the 2nd one even correct? Isn't each `query.Where` returning a different `IQueryable` (or whatever), and not modifying the original? Either way, [Which is faster?](https://ericlippert.com/2012/12/17/performance-rant/) – James Thorpe Jan 05 '17 at 09:17
  • At second section, it will check all 'if' clauses. At first section, if first section until first && is false, it wont check second section after && so it will exit, in that case first code is faster. – onur Jan 05 '17 at 09:19
  • The second piece of code is incorrect. It needs to be `query = query.Where(...)` inside each if-statement block. – Lasse V. Karlsen Jan 05 '17 at 09:26
  • LINQ to what? EF? Objects? With EF, there should be no difference if the same SQL is generated. With objects, each Where is another iterator which does *not* mean another loop. Just one extra call per item – Panagiotis Kanavos Jan 05 '17 at 09:28

1 Answers1

1

I guess second code should be like below:

    if (!String.IsNullOrEmpty(firstname))
    {
        query = query.Where(i => i.FirstName.Contains(firstname));
    }
    if (!String.IsNullOrEmpty(secondname))
    {
        query = query.Where(i => i.FirstName.Contains(firstname));
    }
    if (date!=default(DateTime))
    {
        query = query.Where(i => i.DateOfOrder==date);
    }

but in any case, you may check the final sql query generated and compare them instead.

to get the sql query, you can

  1. write the sql to console by calling dbCtx.Log = Console.Out

  2. profile your sql server and see what queries come in

Rex
  • 2,130
  • 11
  • 12