双层for循环优化
今天测试代码时,发现耗时最多的就出现在以下这个循环中,其中当ds.Tables[0].Rows.Count、dst.Tables[0].Rows.Count数过万时,就特别明显了。
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
for (int j = 0; j < dst.Tables[0].Rows.Count; j++)
{
if (ds.Tables[0].Rows[i]["code"].ToString() == dst.Tables[0].Rows[j]["code"].ToString())
{
dst.Tables[0].Rows[j]["name"] = ds.Tables[0].Rows[i]["name"];
dst.Tables[0].Rows[j]["price"] = ds.Tables[0].Rows[i]["price"];
}
}
}
哪位高手帮指点下
[解决办法]
既然有相等判断,其实你之前先花时间做一个排序会好一些。那么判断是否存在相等记录,只要二分查找就可以了。
[解决办法]
你这种情况直接用Hash表就可以了,性能远高于先排序再用二分查找。时间复杂度仅为 ds的行数 + dst的行数
- C# code
Dictionary<string, DataRow> dict = new Dictionary<string,DataRow>(); foreach (DataRow row in ds.Tables[0].Rows) { dict[row["code"].ToString()] = row; } foreach (DataRow row in dst.Tables[0].Rows) { DataRow dr; if(dict.TryGetValue(row["code"].ToString(), out dr)) { row["name"] = dr["name"]; row["price"] = dr["price"]; } }
[解决办法]
- C# code
for (int i = 0; i < ds.Tables[0].Rows.Count; i++){string code = ds.Tables[0].Rows[i]["code"].ToString();DataRow[] find dst.select("code = '"+code+"'");if(find.length>0){你的赋值语句}}