« July 2009 | Main | September 2009 »
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 8:11 PM | Comments (1) | TrackBack