Question

Is there a difference (performance, overhead) between these two ways of initializing an object:

MyTypedDataSet aDataSet = new MyTypedDataSet();
aDataSet .Merge(anotherDataSet);
aDataSet .Merge(yetAnotherDataSet);

and

MyTypedDataSet aDataSet = anotherDataSet;
aDataSet .Merge(yetAnotherDataSet);

Which do you recommend?

Was it helpful?

Solution

While Keith is right, I suppose the example was simply badly chosen. Generally, it is better to initialize to the “right” object from the beginning and not construct an intermediate, empty object as in your case. Two reasons:

  1. Performance. This should be obvious: Object creation costs time so creating less objects is better.
  2. Much more important however, it better states your intent. You do generally not intend to create stateless/empty objects. Rather, you intend to create objects with some state or content. Do it. No need to create a useless (because empty) temporary.

OTHER TIPS

Those two lines do different things.

The first one creates a new set, and then merges a second set into it.

The second one sets the ds reference to point to the second set, so:

MyTypedDataSet ds1 = new MyTypedDataSet();
ds1.Merge(anotherDataSet);
//ds1 is a copy of anotherDataSet
ds1.Tables.Add("test")

//anotherDataSet does not contain the new table

MyTypedDataSet ds2 = anotherDataSet;
//ds12 actually points to anotherDataSet
ds2.Tables.Add("test");

//anotherDataSet now contains the new table

Ok, let's assume that what you meant was:

MyClass o1 = new MyClass();
o1.LoadFrom( /* some data */ );

//vs

MyClass o2 = new MyClass( /* some data */ );

Then the latter is better, as the former creates an empty object before populating it.

However unless initialising an empty class has a high cost or is repeated a large number of times the difference is not that important.

Your second example does not create a new dataset. It's just a second reference to an existing dataset.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top