Saif Khan
Saif Khan

Reputation: 18782

Re-using DataSets in .net

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()?

Upvotes: 3

Views: 1946

Answers (3)

to StackOverflow
to StackOverflow

Reputation: 124696

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 

Upvotes: 2

NerdFury
NerdFury

Reputation: 19214

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.

Upvotes: 1

Preet Sangha
Preet Sangha

Reputation: 65496

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.

Upvotes: 2

Related Questions