[英]Adding multiple rows to DataTable
我知道有兩種方法可以將新行與數據添加到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];
}
以上兩種方法會給我同樣的結果,即一二三將被添加DataTable
中單獨列。
但我的問題是,兩個步驟之間有什么區別,哪個是更好的表現方式?
一些反編譯觀察
在這兩種情況下,都使用System.Data.DataRowCollection.Add
方法的不同重載。
第一種方法使用:
public void Add(DataRow row)
{
this.table.AddRow(row, -1);
}
第二種方法將使用:
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] = value[i];
,將致電:
public DataColumn this[int index]
{
get
{
DataColumn result;
try
{
result = (DataColumn)this._list[index];
}
catch (ArgumentOutOfRangeException)
{
throw ExceptionBuilder.ColumnOutOfRange(index);
}
return result;
}
}
_list
,我們發現_list
實際上是一個ArrayList
:
private readonly ArrayList _list = new ArrayList();
結論
為了總結上述內容,如果您使用的是dtDeptDtl.Rows.Add();
而不是dtDeptDtl.Rows.Add(dr2);
隨着列數的增加,您將獲得性能下降 ,並將呈指數級增長。 降級的負責行是調用NewRecordFromArray
方法,該方法遍歷ArrayList
。
注意:如果您向表中添加8列,並在for
循環1000000次中進行一些測試,則可以輕松測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.