Tom Gullen
Tom Gullen

Reputation: 61737

Linq when returning count what to select?

I've gotten in the silly habit of doing this:

return 
    (from c in db.tblUserAlerts 
     where c.userID == UserID && !c.hasRead  
     select new { c.ID }).Count();

Is it better (saves memory) to return c.ID as supposed to the entire c record? Example:

return 
    (from c in db.tblUserAlerts 
     where c.userID == UserID && !c.hasRead 
     select c).Count();

Upvotes: 2

Views: 230

Answers (2)

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28698

The most obvious way to write this query is as suggested.

return db.tblUserAlerts.Count(c=>c.userID == UserID && !c.hasRead); 

In this case SQL could execute a COUNT (1) WHERE...

It's very unlikely that your select is going to cost or gain you anything - it's translated into SQL, and the execution difference of COUNT(*) and COUNT(id) is going to be tiny (if it exists at all), as will the execution difference of COUNT(id) and COUNT(1). But why write code that doesn't do anything? There's no need to select anything.

It seems strange that you ask

Is it better (saves memory) to return c.ID as supposed to the entire c record?

but then comment

that's a good idea but I prefer writing them out like above

Do you want to write efficient, clean code that 'saves memory', or do you want to write according to your preferences for no obvious reason? Less code is cleaner code - it's not as if .Count(Exp<>) is an obscure, rarely used overload.

Upvotes: 1

Adam Jones
Adam Jones

Reputation: 721

I think the issue is more how much transformation the data has to go through. For what you are trying to do, I think the most efficient would be:

return db.tblUserAlerts.Count(c=>c.userID == UserID && !c.hasRead);

because you are really only running your data through 1 method and it isn't copying or transforming your data, just counting the things that match the predicate.

EDIT: I looked again at your tags, and see that you have linq-to-sql. If you are using a query provider like LINQ to SQL, the query is translated. I would guess the linq-to-sql query translator would translate to something like:

SELECT count(c.ID) FROM tblUserAlerts WHERE c.userID == 'UserID' AND NOT c.hasRead

in this case there shouldn't be any speed difference whatsoever, except that LINQ-to-SQL might have to do more work in translating your query because there is more in the expression tree. That speed difference would be mostly negligible. My original answer above is more applicable to LINQ-to-Objects. With LINQ-to-SQL unless you are hyper sensitive to any speed decrease (ie you are running this thousands of times in a tight loop) they should be roughly equivalent.

Upvotes: 5

Related Questions