CRITICAL
Rule Definition
From a performance point of view, it is better to call AcceptChanges only once at the end of a loop rather than at each iteration.
Remediation
Move the Acceptchanges call at the end of the loop. Check that the obtained results are the same.
Violation Code Sample
// Define a dataset with a datatable and three columns (keep default values for all)
...
void DisplayMessage( String szAdditionalMsg, long lStart)
{
String szMsg = szAdditionalMsg + Convert.ToString((new System.TimeSpan(DateTime.Now.Ticks)).Ticks - (new System.TimeSpan(lStart)).Ticks);
MessageBox.Show(szMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
void f()
{
DataSet1 ds1 = new DataSet1();
int i = 0; long lStart = 0; String szMsg = "";
lStart = DateTime.Now.Ticks;
for (i=0; i <1000; i++) {
ds1.DataTable1.Rows.Add( new object[] { i.ToString(), i.ToString(), i.ToString() });
ds1.AcceptChanges();
}
DisplayMessage("#Ticks with AcceptChanges in the loop: ", lStart);
}
Fixed Code Sample
// Define a dataset with a datatable and three columns (keep default values for all)
...
void DisplayMessage( String szAdditionalMsg, long lStart)
{
String szMsg = szAdditionalMsg + Convert.ToString((new System.TimeSpan(DateTime.Now.Ticks)).Ticks - (new System.TimeSpan(lStart)).Ticks);
MessageBox.Show(szMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
void f()
{
DataSet1 ds1 = new DataSet1();
int i = 0; long lStart = 0; String szMsg = "";
lStart = DateTime.Now.Ticks;
for (i=0; i <1000; i++) {
d12.DataTable1.Rows.Add( new object[] { i.ToString(), i.ToString(), i.ToString() });
}
ds1.AcceptChanges();
DisplayMessage("#Ticks with AcceptChanges outside of the loop: ", lStart);
}
Reference
See .Net 2005 sample provided.
Second loop is about 50 times quicker.
Related Technologies
.Net
Technical Criterion
CWE-1050 - Excessive Platform Resource Consumption within a Loop
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.