Lazy loading, immediate loading, performance

by volkanuzun 10/28/2008 3:34:00 PM

While i am still reading the linq book i mentioned yesterday, i also  keep working on the projects at work (i need money to pay the bills). One of the pages i did using linq was very slow, and i ran the profile and guess what, lot's queries were sent to the  database by linq. I decided to read more about linq :) before i use it in the production system. At chapter 4, i read about lazy loading and immediate loading, and decided to share it here. I am sure all of you know about linq and its lazy loading mechanism, although this is most of the time performance saver, if you dont really look into your code, this also could kill your app. Here is a simple code example using northwind database (the code is from "Programming LINQ" Ms Press)

var query = from c in Customers
                  where c.Orders.Count>20
                  select c;

foreach(var row in query){
    Console.WriteLine(row.CompanyName);
    foreach(var order in <span class="Apple-style-span" style="font-weight: bold">row.Orders</span>){
         Console.WriteLine(order.OrderID);
    }
}

 

The bold part is the performance killing part, each time you ask for row.Orders, LINQ makes a query to the Orders table to get the related Orders, and this row.Count times inner query. However if you have loaded the Orders while you are loding the Customers, then you dont need this inner query. So you should really look at your code and decide if you need lazy loading or immediate loading. BTW here is the immediate loading:

DataLoadOptions loadOptions = new DataLoadOptions();
loadOptions.AssociateWith<Customer>(c=>from o in c.Orders
                                                               where o.OrderDate.Value....);
loadOptions.LoadWith(Customer>(c=>c.Orders);
db.LoadOptions = loadOptions;

 

You should really buy and read this book btw :)

 

Tags:

LINQ

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



About the author

Volkan Uzun




E-mail me Send mail

Twitter

Calendar

<<  January 2009  >>
MoTuWeThFrSaSu
2930311234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar

Flickr Badge

www.flickr.com
This is a Flickr badge showing public photos from volkanuzun. Make your own badge here.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2009

Sign in