Improving performance of read only selects in entity framework by turning off tracking with AsNoTracking method

We had a new contractor start the other day in work and he brought to my attention the ability to tell entity framework to not track (e.g. bypass the ObjectStateManager) the results of a query using the AsNoTracking method which if you are only loading entities once may result in a performance boost.

The order of the performance boost appears to be less significant in EF 6 than it is in EF 5 in terms of both time to complete and memory usage. The specific performance increase achieved will of course depend on how complex your model is and how many rows your looking to pull back from the database. In this example EF 5 showed a time to complete difference of 9% and EF 6 showed a difference of 3% between queries executed with and without tracking enabled.

I’m not sure how I missed this one before but this method appears very useful when querying read only data which you might just be using to populate a drop down or similar HTML element for example. Examples of how AsNoTracking can be implemented are on the MSDN article ‘Performance Considerations for Entity Framework 4, 5, and 6

As that article points out however be mindful that bypassing the ObjectStateManager disables the cache and thus if you retrieve the same entities multiple times from the same context, using AsNoTracking could actually worsen the performance of your queries. 

Leave a Reply

Your email address will not be published.