static void Main() { var db = new TelerikAcademyEntities(); Stopwatch watch = new Stopwatch(); //Try with many ToList() watch.Start(); var employees = db.Employees.ToList() .Select(employee => employee.Address).ToList() .Select(address => address.Town).ToList() .Where(town => town.Name.Equals("Sofia")).ToList(); watch.Stop(); var performanceWithManyListings = watch.Elapsed; watch.Reset(); //Try with single ToList() watch.Start(); employees = db.Employees .Select(employee => employee.Address) .Select(address => address.Town) .Where(town => town.Name.Equals("Sofia")).ToList(); watch.Stop(); var performanceWithSingleListing = watch.Elapsed; //Performance result Console.WriteLine("Performance with many ToList(): {0}{1}Performance with single ToList(): {2}", performanceWithManyListings, Environment.NewLine, performanceWithSingleListing); //Second option is about 7 times faster! }
public static void Main() { Stopwatch watch = new Stopwatch(); var db = new TelerikAcademyEntities(); //Try witout include var employees = db.Employees; watch.Start(); foreach (var employee in employees) { Console.WriteLine("Name: {0} {1}, Department: {2}, Town: {3}", employee.FirstName, employee.LastName, employee.Department.Name, employee.Address.Town.Name); } watch.Stop(); var timeElapsedWithoutInclude = watch.Elapsed; //Reset clock watch.Reset(); //Try with Include var employeesWithIncluded = db.Employees.Include("Department").Include("Address.Town"); watch.Start(); foreach (var employee in employeesWithIncluded) { Console.WriteLine("Name: {0} {1}, Department: {2}, Town: {3}", employee.FirstName, employee.LastName, employee.Department.Name, employee.Address.Town.Name); } watch.Stop(); var timeElapsedWithInclude = watch.Elapsed; //Performance results Console.WriteLine("Time requred without Include: {0}{1}Time required with Include: {2}", timeElapsedWithoutInclude, Environment.NewLine, timeElapsedWithInclude); //Without Include it does so much queries that I couldn't count them int he profiler. //With Include it does only two queries to the database. //No wonder second option is waaaay faster! }