LINQ Object Query Performance

I have a stupid question. I would like to know if there is a performance difference between these two queries:

var cObject = from cust in entities.Customer 
              where cust.id == cid
              select cust;

      

and

var cObject = entities.Customer.First( c=> c.id == cid);

      

My query only returns one record as I am querying for the primary key. But don't they matter?

+2


a source to share


4 answers


Efficiency, they should be similar.



The type is wise, they are different. The first one returns an IEnumerable IQueryable object with a single element. The second actually returns a Customer object.

+3


a source


If your LINQ provider supports the notion of a "single record query", a using query is First

likely to be slightly faster.



Note that you can use the first one and then do cObject.First()

it to get the same effect.

+1


a source


As Craig Stunts points out in the comments on this question, you should be careful with profiling your Linq code, as delayed lazy loading can skew the profiling results.

To get a clear read, you need to call ToList()

to force the request, and then you have to do the same in the second example to make it apples apples.

In any case, if the second query were rewritten to return an IEnumerable IQueryable with one client object instead of one client object, the two statements would be functionally identical.

+1


a source


No performance.

For the first time Microsoft introduced

var cObject = entities.Customer.First( c=> c.id == cid);

      

Edit: returns IQueryable

Then they added sugar to it to make the job easier.

var cObject = from cust in entities.Customer 
          where cust.id == cid
      select cust;

      

Edit Returns customer object

0


a source







All Articles