There's been alot of blogging about where lazy loads are appropriate and where they aren't so I figured I'd toss my opinion into the wild.
Like most things in developing, there is no “silver bullet” for whether or not to lazy load. There are advantages and disadvantages to both solutions, which you can apply to your runtime environment to make a logical decision.
Advantages of Lazy Loads:
- Decreased Network Bandwidth- You're reading data out in smaller chunks. This can be fairly significant when the pipe is limited.
- Decreased Memory Footprint- Why load 100 lines of data into memory when only 5 are going to be used?
- Better Handling of Concurrency- Obviously the late loading gives you “fresher“ data in the object, which reduces the chance of invalid data.
Disadvantages of Lazy Loads:
- Increased Database Calls- Now instead of grabbing everything in one fell swoop, you're going to have to make a database call for each child object. This can get ugly when dealing with collections.
- Latency- If you're in a situation where the caller is at an unknown location (say a public webservice) you are probably better off making as few calls as possible. On a fast intranet this is less of an issue.
- User Experience With Latency- This is a big one. If your program has already loaded some of the object, the user tends to assume the whole data is there. When it isn't, and they have to wait for a call, this can cause some frustration.
That being said, here's some general thoughts I have:
- If you have a powerful database and the database calls are on an intranet, that's a positive situation for lazy loading. Idle CPU time is wasted money. I once worked for an employer that had a $40,000 badass database server and pretty crappy clients. The architects insisted on downloading as much of the data as possible to the client and manipulating it all there in memory. Needless to say the client workstations were slow as hell bogged down by data not being used while the $40,000 database server idled quietly.
- If you have the opposite: limited database and powerful clients, go ahead and send them as much of the information as you're comfortable with.
- Do some performance testing and see how expensive a call is.
- Most importantly anticipate how your objects are going to be used. My company's asset management program actually uses both lazy loading and pre-emptive loading. Basically if I have object A, with collections of objects B and C inside it, I sat down and said “Ok, anytime I load object A, what are my chances of needing information from B and C?“ If the chances were high then I loaded it with A, if it was only being used once in a blue moon like in a report, lazy load.
