添加多行数据表 [英] Adding multiple rows to DataTable
问题描述
我知道两种方法的数据到添加新行数据表
I know two ways to add new row with data to a DataTable
string[] arr2 = { "one", "two", "three" };
dtDeptDtl.Columns.Add("Dept_Cd");
for (int a = 0; a < arr2.Length; a++)
{
DataRow dr2 = dtDeptDtl.NewRow();
dr2["Dept_Cd"] = DeptCd[a];
dtDeptDtl.Rows.Add(dr2);
}
for (int a = 0; a < arr2.Length; a++)
{
dtDeptDtl.Rows.Add();
dtDeptDtl.Rows[a]["Dept_Cd"] = DeptCd[a];
}
以上两种方法会给我同样的结果,即一二三将在数据表
在单独的行加入。
但我的问题是,有什么步骤,哪一个是更好的方式表现明智?
But my question is that what is the difference between both the steps and which one is better way performance wise?
推荐答案
有些反编译器观察
在这两种情况下,不同的过载 System.Data.DataRowCollection.Add
正在使用的方法。
In both scenarios, a different overload of the System.Data.DataRowCollection.Add
method is being used.
第一种方式使用:
public void Add(DataRow row)
{
this.table.AddRow(row, -1);
}
第二种方法将使用:
The second approach will use:
public DataRow Add(params object[] values)
{
int record = this.table.NewRecordFromArray(values);
DataRow dataRow = this.table.NewRow(record);
this.table.AddRow(dataRow, -1);
return dataRow;
}
现在,来看看这小兽:
internal int NewRecordFromArray(object[] value)
{
int count = this.columnCollection.Count;
if (count < value.Length)
{
throw ExceptionBuilder.ValueArrayLength();
}
int num = this.recordManager.NewRecordBase();
int result;
try
{
for (int i = 0; i < value.Length; i++)
{
if (value[i] != null)
{
this.columnCollection[i][num] = value[i];
}
else
{
this.columnCollection[i].Init(num);
}
}
for (int j = value.Length; j < count; j++)
{
this.columnCollection[j].Init(num);
}
result = num;
}
catch (Exception e)
{
if (ADP.IsCatchableOrSecurityExceptionType(e))
{
this.FreeRecord(ref num);
}
throw;
}
return result;
}
尤其注意 this.columnCollection [I] [NUM] =值[I];
,它将调用:
public DataColumn this[int index]
{
get
{
DataColumn result;
try
{
result = (DataColumn)this._list[index];
}
catch (ArgumentOutOfRangeException)
{
throw ExceptionBuilder.ColumnOutOfRange(index);
}
return result;
}
}
展望未来,我们发现,实际上 _list
是的ArrayList
:
private readonly ArrayList _list = new ArrayList();
结论
为了总结上述情况,如果您使用的是 dtDeptDtl.Rows.Add();
而不是 dtDeptDtl.Rows.Add(DR2 );
,你会得到一个性能下降这将成倍增加,因为列数的增长。对于降解的负责线是调用 NewRecordFromArray
方法,它遍历一个的ArrayList
。
In order to summarize the above, if you are using dtDeptDtl.Rows.Add();
instead of dtDeptDtl.Rows.Add(dr2);
, you will get a performance degradation which will increase exponentially, as the number of columns grows. The responsible line for the degradation is call to the NewRecordFromArray
method, which iterates over an ArrayList
.
的注:这可以如果添加,让我们说,8列表,并提出一些测试,在为
循环100万倍很容易地测
Note: This can be easily tested if you add, let's say, 8 columns to the table and make some tests in a for
looping 1000000 times.
这篇关于添加多行数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!