为了我自己的启发,我决定测试 DataTable.ImportRow 与 DataTable.Merge 的比较速度。我发现 DataTable.ImportRow 比 DataTable.Merge 慢很多。在极少数情况下,这两个函数的处理时间相同。在更罕见的情况下,ImportRow 比 Merge 更快。
下面是我的测试结果和代码。
DataTable dt = new DataTable();
dt.Columns.Add("customerId", typeof(int));
dt.Columns.Add("username", typeof(string));
for (int i = 0; i <= 100000; i++)
{
DataRow myNewRow;
myNewRow = dt.NewRow();
myNewRow["customerId"] = 1;
myNewRow["username"] = "johndoe";
dt.Rows.Add(myNewRow);
}
// First Duration
DateTime startTime1 = DateTime.Now;
DataTable dt2 = new DataTable();
dt2 = dt.Clone();
for (int i = 0; i < dt.Rows.Count; i++)
dt2.ImportRow(dt.Rows[i]);
DateTime stopTime1 = DateTime.Now;
// End First Duration
TimeSpan duration1 = stopTime1 - startTime1;
// Second Duration
DateTime startTime2 = DateTime.Now;
DataTable dt3 = new DataTable();
dt3 = dt.Clone();
dt3.Merge(dt);
DateTime stopTime2 = DateTime.Now;
// End Second Duration
TimeSpan duration2 = stopTime2 - startTime2;
编辑:根据建议更新代码 -
DataTable dt = new DataTable();
dt.Columns.Add("customerId", typeof(int));
dt.Columns.Add("username", typeof(string));
DataColumn[] key = new DataColumn[1];
key[0] = dt.Columns[0];
dt.PrimaryKey = key;
for (int i = 0; i <= 100000; i++)
{
DataRow myNewRow;
myNewRow = dt.NewRow();
myNewRow["customerId"] = i;
myNewRow["username"] = "johndoe";
dt.Rows.Add(myNewRow);
}
// First Duration
//DateTime startTime1 = DateTime.Now;
Stopwatch sw1 = new Stopwatch();
sw1.Start();
DataTable dt2 = new DataTable();
dt2 = dt.Clone();
for (int i = 0; i < dt.Rows.Count; i++)
dt2.ImportRow(dt.Rows[i]);
//DateTime stopTime1 = DateTime.Now;
sw1.Stop();
// End First Duration
TimeSpan duration1 = sw1.Elapsed;
// Second Duration
//DateTime startTime2 = DateTime.Now;
Stopwatch sw2 = new Stopwatch();
sw2.Start();
DataTable dt3 = new DataTable();
dt3 = dt.Clone();
dt3.Merge(dt);
sw2.Stop();
//DateTime stopTime2 = DateTime.Now;
// End Second Duration
TimeSpan duration2 = sw2.Elapsed;
label3.Text = duration1.Milliseconds.ToString();
label4.Text = duration2.Milliseconds.ToString();
最佳答案
关于c# - ImportRow 与合并速度问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3363208/