Friday, February 4, 2011

Object initialization in C# (.Net)

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?

  • 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.

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

  • 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.
    Daniel James : Also, for some cases (but not the example) if you fully initialize the object at creation time, the object can be immutable.
  • Indeed, I'm sorry. I make a mistake while adding the code snippets.

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

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

0 comments:

Post a Comment