I have situation in which i’m compelled to retrieve 30,000 records each to 2 datatables.I need to do some manipulations and insert into records into the SQL server in Manipulate(dt1,dt2) function.I have to do this in 15 times as you can see in the for loop.Now I want to know what would be the effective way in terms of memory usage.I’ve used the first approach.Please suggest me the best approach.
(1)
for (int i = 0; i < 15; i++)
{
DataTable dt1 = GetInfo(i);
DataTable dt2 = GetData(i);
Manipulate(dt1,dt2);
}
(OR)
(2)
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
for (int i = 0; i < 15; i++)
{
dt1=null;
dt2=null;
dt1 = GetInfo();
dt2 = GetData();
Manipulate(dt1, dt2);
}
In theory, the first example is more efficient, because in the second example you start by creating two
DataTableobjects that won’t get used. However, these twoDataTableobjects contain little data, so the overhead in memory usage is minimal and almost impossible to measure.Trying to optimize this example for performance seems to me premature optimization, what of course is a bad thing. You should go for the most readable solution first, and only when it is too slow, optimize it.
In your case however, the first code snippet is definitely more readable than the second one, because it is less code, the scope of variables is much shorter and you don’t needlessly reset the instances to
null.