-4

Case 1:

for(int =0;i<1000;i++)
{
 Datatable dt=new Datatable();
 //Perform some operation
 dt.Dispose();
}

Case 2:

Datatable dt=new Datatable();
for(int =0;i<1000;i++)
{
 //Perform some operation
 dt=null;
}

i want to use a data table in a loop, which case would be more efficient: creating and destroying an object in the loop everytime or creating it before the loop?

vijay
  • 2,646
  • 2
  • 23
  • 37

3 Answers3

0

Try this

Edit: if you want to keep same structure then you can clear items on each loop

Datatable dt =new Datatable();
//add columns to your datatable
for(int i=0;i<1000;i++)
{    
  dt.Items.Clear();
  //your other code
}
rs.
  • 26,707
  • 12
  • 68
  • 90
  • rs: table structure will remain same every time. would it be good to create new dt object at every iteration? – noviceprogrammer Mar 09 '13 at 04:56
  • if table structure is same then don't use new keyword........ you can remove all the rows for next iteration. – andy Mar 09 '13 at 05:00
0

Case 2 is more efficient but it should be like below

Datatable dt = null;
for(int i = 0; i < 1000; i++)
{    
 dt = new Datatable();
 //Perform some operation
 dt = null;//or dt.Dispose();
} 
andy
  • 5,979
  • 2
  • 27
  • 49
  • Check [this](http://stackoverflow.com/questions/7884083/c-declaring-a-variable-inside-for-loop-will-it-decrease-performance) – andy Mar 09 '13 at 04:59
0

Case 2 would be more efficient. Object constructors are relatively expensive operations for the CPU. Constructing one object and assigning values to its members is different than destroying an object and constructing. Destroying an object and recreating it is the equivalent of tearing a house down and rebuilding it every time new tenants move in.

RouteMapper
  • 2,484
  • 1
  • 26
  • 45