1

Is there a performance difference between:

ctx
   .Students
   .Join(
      ctx.Countries, 
      q => q.CountryId, 
      q => q.CountryId, 
      (c,s) => new { c,s })
   .Where(q => q.c.CountryName= "USA")
   .Select(q => q.s.StudentName)
   .ToList();

and:

ctx
   .Students
   .Join(
      ctx.Countries.Where(q => q.CountryName == "USA"), 
      q => q.CountryId, 
      q => q.CountryId, 
      (c,s) => s)
   .Select(q => q.StudentName)
   .ToList();

If so, which query is preferable ?

koryakinp
  • 3,989
  • 6
  • 26
  • 56
  • Is this Linq executed in memory or this is Linq which generate sql query? Did you run your both cases? – Fabio May 03 '18 at 18:31
  • @Fabio, LINQ which generate SQL query. But in case it executed in memory, how the answer would be different ? Yes, I did run both cases. – koryakinp May 03 '18 at 18:35
  • If you ran both cases - check generated SQL queries or use SQL profiler for performance details or copy generated queries and run it, for example, in SQL server management studio. – Fabio May 03 '18 at 18:51

1 Answers1

2

General rule is filter left, meaning do your filters first. With compiled languages like C# though, you really should just test it. Throw some times stamps and see how long it takes to execute with large queries.

The reason being is the compiler will often optimize your code for you. The code that is actually ran is not the code you write, so write code for readability and let the compiler optimize and then test for performance. If performance is poor or needs improvement then adjust.

Keith
  • 98
  • 4
  • Sadly compiler have very little to do in OP's case, because performance will mostly depend on what sql query will be generated. – Fabio May 03 '18 at 20:04