« A Few Tips For Taking a SQL Server Database Offline | Main | "File not found" CryptographicException »

August 19, 2009

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

  116         private static IEnumerable<string> GetNames()

  117         {

  118             using (var dc = new MyDataContext())

  119             {

  120                 // This is bad news!

  121                 // This will return alot of columns

  122                 //  that won't even be used.

  123                 var userNames = from u in dc.UserSet

  124                                 select u;

  125 

  126                 // SQL Server Profiler will show you that all the

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

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

  129             }

  130         }


Good

  116         private static IEnumerable<string> GetNames()

  117         {

  118             using (var dc = new MyDataContext ())

  119             {

  120                 // Just get the Name.

  121                 // Don't waste database and network resources!

  122                 var userNames = from u in dc.UserSet

  123                                 select u.Name;

  124 

  125                 return userNames.ToList();

  126             }

  127         }

Posted by Bill Simpkins at August 19, 2009 8:11 PM

Trackback Pings

TrackBack URL for this entry:
http://blog.logos.com/mt-cgi/mt-tb.cgi/301

Comments

Of course, line 128 of the first example could be rewritten as

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

to achieve the same result, but the single query is less code.

Posted by: Darren at August 19, 2009 10:54 PM

Post a comment




(you may use HTML tags for style)