I’m creating a repository in EF4. For one of the methods a password and username is used to verify a user. The method returns a count of users so a 0 means they don’t exist and a 1 they do. Would it make much of a difference if I just returned a user object and checked it for null?
Share
Technically the most efficient way would probably be to use the
Any()extension method. If you return an object there is the cost of filling that object. If you return a count, then there is the cost of going through every record (after the where clause has been applied) and counting them.Any()should useExistsin sql, and therefore, SQL server can stop as soon as it finds the first record.Ultimately though, I agree with the others, this isn’t a place you want to start optimizing right away. Donald Knuth probably has the best quote about this:
“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil”.
For instance, let’s say you have this method return a bool and you use the
Any()method. Later in the request, you might need to pull the user object out of the database (this could be something you end up doing a lot). Now, by optimizing early, you’ve actually increased the number of calls to the database.HTH