0

Is there any performance difference between the following two queries?

CustomerProduct customerProduct = db.CustomerProducts.SingleOrDefault(p => object.Equals(p.Customer, this));

CustomerProduct customerProduct = (from p in db.CustomerProducts where object.Equals(p.Customer, this) select p).SingleOrDefault();

Perhaps there's another, even faster one?

SharpAffair
  • 5,558
  • 13
  • 78
  • 158

1 Answers1

1

In terms of compilation, they should be compiled into the the same code; Linq is just syntactic sugar which the compiler will interpret for you. That being said, not all linq queries will be compiled in the way you expect and regardless you should always check the generated sql using the ObjectQuery cast + ToTraceString method.

Skyrim
  • 865
  • 5
  • 6
  • 1
    Or if you're using SqlServer, you can use Sql Profiler to inspect the query being sent. – Skyrim Jun 03 '12 at 01:36
  • Would that imply that comparing an attribute from a row in Table A to retrieve rows from Table B would be the same as doing a join on those tables with the given attribute? I have something like this I need to implement in the near future and was thinking "Oh I'm going to have to write SQL for this query because looping over both tables is going to be inefficient." – evanmcdonnal Jun 03 '12 at 01:44
  • 1
    @evanmcdonnal Hmm...I'm not sure I understand wat you mean. Let me try to answer in this way: if you were making an actual sql query and it involved a join, then you can (in most cases) convert it into a linq query including that (innner/outer) join. That way you wouldn't have to do the comparison in memory. – Skyrim Jun 03 '12 at 01:50