Editorials

IQueryable and IEnumerable Are Not the Same

Yesterday I had a good comment in regards to optimizing Dot Net code http://bitonthewire.wpengine.com/editorials/readed.aspx?id=3284, and using ToList() as a materializer of Linq statements. Craig writes:

One comment on point #1: when you *do* ToList() your query be sure that you have already included all your Where’s.


When you ToList() the query will execute and all the data will head from SQL’s disk to your memory. It can sometimes be useful to keep your IQueryable query around for later computations and selectively choose some sub-selects to call ToList() on.


Try to materialize the query when it contains the most restrictive set of data you will be working with.

This is all great advice when your Linq statement is pulling from a database. However, let us not forget that Linq is a set language that can work with any IEnumerable object. This means working with many different types of collections such as arrays, lists, dictionaries, concurrent bags, hash tables, etc.

I work with a lot of engines that may interact with data from a database, or other services. The key I have learned in those instances is that, although I can sometimes write looping code that out-performs Linq queries, it is not worth the fragility of the necessary code. A better solution is to be sure anytime a collection is enumerated, that the results are materialized before the enumeration begins.

There is a big difference you may want to research between objects that are IQueryiable and IEnumerable. Knowing and handling these two different types correctly can enhance your application performance as well.

Cheers,

Ben