views:

101

answers:

3

Is it a good idea to re-use a dataset in .net? What I mean is...I have the following code which loops a gridview

For Each row in GridView
  ds = New DataSet
  ds.ReadXML(GetStream(row.Field))
  ... export the dataset
Next

What I am doing in the loop is creating a new instance of the DataSet. Can't I just call ds.Clear() and then reuse it via the ds.ReadXML()?

+1  A: 

You weigh reuse with other performance considerations. Generally speaking I don't do optimisations like this until they become necessary. And then only if I have numbers to prove that it's needed.

Preet Sangha
I agree, however in this particular case I have to loop 200 rows in the GridView and fetch a dataset from the DB averaging 2MB.
Saif Khan
That's for each record.
Saif Khan
If that is true, your fetching of the data is far more expensive than the amount of time it takes for the framework to give you a new empty DataSet. var ds = new DataSet() takes less than 10 ms, your data fetching operation takes probably 500 times that long, so the optimization of new vs. Clear() isn't worth it.
NerdFury
+1  A: 

The semantics are different: DataSet.Clear deletes all the data (rows), but keeps the schema (tables and relations).

In your sample, it looks like the tables are being created from the ReadXml method (which can read schema as well as data).

DataSet.Clear would probably work as long as you are certain all Xml documents have the same schema, but using New is more robust and expresses your intent better.

However if you were reading data only, as in the following sample, DataSet.Clear might be a better choice as it avoids you repeatedly generating the schema.

ds = New DataSet 
... code to create the schema (Tables, Columns, Relations)

For Each row in GridView 
  ds.ReadXML(GetStream(row.Field), XmlReadMode.IgnoreSchema) 
  ... export the dataset 
  ds.Clear
Next 
Joe
I just read http://www.pcreview.co.uk/forums/thread-1242477.php that a call to ReadXML() actually resets the dataset before loading.
Saif Khan
A: 

You might be able to do that, but object creation is so inexpensive and you have no risk of side effects, there isn't any reason not to create the new object.

NerdFury