Anu*_*nuj 9 c# asp.net datatable
我知道两种方法来添加带有数据的新行 DataTable
string[] arr2 = { "one", "two", "three" };
dtDeptDtl.Columns.Add("Dept_Cd");
Run Code Online (Sandbox Code Playgroud)
for (int a = 0; a < arr2.Length; a++)
{
DataRow dr2 = dtDeptDtl.NewRow();
dr2["Dept_Cd"] = DeptCd[a];
dtDeptDtl.Rows.Add(dr2);
}
Run Code Online (Sandbox Code Playgroud)
for (int a = 0; a < arr2.Length; a++)
{
dtDeptDtl.Rows.Add();
dtDeptDtl.Rows[a]["Dept_Cd"] = DeptCd[a];
}
Run Code Online (Sandbox Code Playgroud)
上述两种方法都会给我相同的结果,即One Two Three将被添加DataTable
到单独的行中.
但我的问题是,两个步骤之间有什么区别,哪个是更好的表现方式?
一些反编译观察
在这两种情况下,System.Data.DataRowCollection.Add
都使用了该方法的不同重载.
第一种方法使用:
public void Add(DataRow row)
{
this.table.AddRow(row, -1);
}
Run Code Online (Sandbox Code Playgroud)
第二种方法将使用:
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;
}
Run Code Online (Sandbox Code Playgroud)
现在,看看这个小野兽:
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;
}
Run Code Online (Sandbox Code Playgroud)
特别是,请注意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;
}
}
Run Code Online (Sandbox Code Playgroud)
展望未来,我们发现实际上_list
是ArrayList
:
private readonly ArrayList _list = new ArrayList();
Run Code Online (Sandbox Code Playgroud)
结论
为了总结上述内容,如果使用dtDeptDtl.Rows.Add();
而不是dtDeptDtl.Rows.Add(dr2);
,则随着列数的增加,性能会下降,并且会呈指数级增长.降级的负责行是对NewRecordFromArray
方法的调用,该方法遍历一个ArrayList
.
注意:如果您向表中添加8列,并在for
循环1000000次中进行一些测试,则可以轻松测试.
归档时间: |
|
查看次数: |
32510 次 |
最近记录: |