views:

1381

answers:

5

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?

+5  A: 

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.

Keith
+4  A: 

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

Joel Coehoorn
+1  A: 

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.
Konrad Rudolph
Also, for some cases (but not the example) if you fully initialize the object at creation time, the object can be immutable.
Daniel James
A: 

Indeed, I'm sorry. I make a mistake while adding the code snippets.

iulianchira
Your code change isn't relevant for the argumentation, though. It simply involves one more DataSet.
Konrad Rudolph
You still have the same problem, the first example creates a new 3rd dataset, while the next example changes anotherDataSet.
Keith
+1  A: 

Don't use Typed Datasets period

+1: Hours of pain because of these things. I now lean toward custom classes and generics. Let the db enforce all the db stuff.
jcollum