Reputation: 847
Is there is a difference between these two approaches ?
In this approach I am using the getter to initialize the DataTable
public DataTable Res
{
get
{
if (Res == null)
{
Res = GetDataTable();
}
return Res ;
}
private set;
}
vs.
In this approach I am using the constructor to initialize the DataTable
public class XYZ
{
public DataTable Res{ get; private set;}
//constructor
public XYZ()
{
Res= GetDataTable();
}
}
This variable is used on an ASP.net page to fill a DropDown List. Which will perform better ?
Edit:-
This is used in a web application where data will not change. I bind this table to a dropdown list in Page_Load event.
Upvotes: 2
Views: 3353
Reputation: 57919
The question is whether a given instance of class XYZ
will always need and use the DataTable
.
If not, then you'd want to lazy-initialize (using your getter), so as to avoid doing the work up front for nothing.
If you will always need it, then the next question is whether there is potentially any substantive delay between instantiation of the class and a call to the Res
property. If so, then loading the data upon instantiation could mean your data is a bit more stale than it would be if you waited until the property getter is called.
The flip-side to that is not necessarily applicable in a web scenario, but in other applications one would want to consider whether a call to the property needs to be highly responsive to keep the UI from freezing. Preloading the data might be preferable in such a scenario.
Upvotes: 2
Reputation: 38077
Yes there is a difference. The first method is called lazy instantiation, which means you wait until the object is used before it is instantiated. The nice thing about doing this is that you are waiting until the last possible second to use up the memory and processor that is required to setup the object.
The second method instantiates the object as soon as you create the class. The downside of doing this is if you never use the object, then you wasted the time to create the object and the memory while the object was allocated.
Upvotes: 1