Entity Framework Performance Tip - Be a Minimalist

Only get the data you need! This not only applies to Entity Framework query performance, but just about every situation were code interacts with data. It is a simple rule to follow, but yet I see it broken all the time. Breaking this rule is one of the top three reasons I’ve seen for slow Entity Framework query performance. I may discuss the other two in later posts …

Bad

private static IEnumerable<string> GetNames()
{
  using (var dc = new MyDataContext())
  {
    // This is bad news!

    // This will return alot of columns

    //  that won't even be used.

    var userNames = from u in dc.UserSet
      select u;
   
    // SQL Server Profiler will show you that all the

    //  columns are fetched when you call "ToList()".

    return userNames.ToList().Select(u => u.Name);
  }
}

Good

private static IEnumerable<string> GetNames()
{
  using (var dc = new MyDataContext ())
  {
    // Just get the Name.

    // Don't waste database and network resources!

    var userNames = from u in dc.UserSet
      select u.Name;
 
    return userNames.ToList();
  }
}

Posted by Bill Simpkins on August 19, 2009