Monday, October 1, 2012

Tips To Improve Entity framework Query Performance

In this blog, we will discuss about the few tips and techniques to improve the entity framework query performance

  • Object tracking turned off 
  • Turn off automatic DetectChanges
  • Avoid the Using block
  • Lazy Loading

1. Object tracking turned off :
when we loads entity in local memory; by deafult it tracks all changes of entity like entity property value changes or deletion of entity and this feature is only beneficial when you want to update the existing entity and but if you only want to read data and you dont want to update entity, then it will be additioanl overload and it will degrade the query performace.

AsNoTracking() function is very useful in writing of no tracking query and it executes very fast because there is no need to store any entity change information.

Example  :
   DbContext context = new DbContext()
   var projects = context.Projects
        .AsNoTracking()
        .ToList();


2. Turn off automatic DetectChanges :
if your application context is not making any entity update or its making bulk insert or update then you can turn off the autoDetectChanges but make sure it is happened only in try/cacth-finally scope

Example :
DbContext context = new DbContext()
context.Configuration.AutoDetectChangesEnabled = false;

3. Avoid the Using block  to create the instance of ObjectContext. :
it takes the lots of times to initialization of ObjectContext and during the initialization, it performs the several steps

  •  Initialize Context (needs to load schema/table metadata from resources)
  •  Validate context
  •  Open connection to DB
  •  Execute submitted SQL script 
  •  Clean up and close DB          
so if you are creating object of DbContext by using  'Using' block and if exection control go out scope of using block, it automatcally will dispose dbContext object.

using (var context = new DbContext())
{
      var projects = context.Projects
        .AsNoTracking()
        .ToList();
}

4. Lazy Loading :
use lazy loading feature and avoid the unnecessary object loading and more information @ Entity Framework - Eager Loading 

5.Examine queries sent to the Database - use ObjectQuery.ToTraceString() to get the raw SQL query what EF is sending to database or you can log sql statement and more information @ Entity Framework - Log SQL Statement 

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...