Hacker News new | ask | show | jobs
by MartinCron 5879 days ago
Similarly, it is very easy and intuitive and horribly inefficient to write something like:

int countOfThings = DatabaseRepositoryType.GetThings().Count();

As it will go to the database, pull all of the matching rows locally, create all of the objects, and then iterate through them just increment a counter. Creating a .GetCount() method which calls down to a SQL "SELECT COUNT()" query is more work to write, but runs about a thousand times faster.

1 comments

This is not quite correct.

The SQL generated in this case depends on the return type of GetThings(). If it returns an IEnumerable<> then it is indeed a terrible thing to do, but if it returns an IQueryable<> then the SQL will be a SELECT COUNT() query, and no objects will be created.

Care does have to be taken when writing this sort of code!