I lazy load all my members. I have been doing this for a while and simply taken lazy load to be a good thing at face value.
Let's say we have
public class SomeClass
{
public int anInt;
public SomeReferenceType member1;
public SomeClass()
{
//initialize members in constructor when needed (lazy load)
anInt = new int();
member1 = new SomeReferenceType();
}
}
Are there any disadvantages to doing things this way? Is this a proper lazy load pattern? Does it make sense to lazy load a value type (with modern RAM does it even matter)?
public class SomeClass
{
public int anInt;
public SomeReferenceType member1 = new SomeReferenceType();
public SomeClass()
{
}
}
Better performance—lazy loading helps you reduce the amount of images required to load when the page is first loaded. This means the page sends less resource requests, uses less bytes when downloading files, and requires less network bandwidth per user.
Lazy-loading images and video reduces initial page load time, initial page weight, and system resource usage, all of which have positive impacts on performance.
Lesser the round trips, better will be the performance. For example, if on a given page, you are only displaying Departments, then there is no reason for Eager Loading related Employees data. Hence, in this case, Lazy Loading works best.
First of all, initializing a member inside the constructor isn't lazy loading.
Lazy Loading is initializing the member the first time it is requested. A simple example in .NET (with some double-check locking so we don't have threading issues):
public class SomeClass
{
private object _lockObj = new object();
private SomeReferenceType _someProperty;
public SomeReferenceType SomeProperty
{
get
{
if(_someProperty== null)
{
lock(_lockObj)
{
if(_someProperty== null)
{
_someProperty= new SomeReferenceType();
}
}
}
return _someProperty;
}
set { _someProperty = value; }
}
}
Luckily, if you're using .NET 4, you can now user the Lazy<T>
Class which handles the issues for you and makes things a lot easier.
Second of all, lazy loading is a good idea when you have many members that could be costly to load and you're sure that you're going to be using all of those values. That cost would cause the type to be un-necessarily slow to instantiate.
Lazy Loading just for the sake of lazy loading is adding unnecessary complexity to your code and could cause issues down the road if done improperly (when dealing with threading, for example).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With