C# if-else vs try-catch 效能比較[在迴圈800次時 相差100倍]
try-catch
while (DataReader.Read())
{
Strid = DataReader[“id”].ToString();
Struid = DataReader[“uid”].ToString();
Strname = DataReader[“name”].ToString();
Strtype = DataReader[“type”].ToString();
Strstatus = DataReader[“status”].ToString();
if (Strstatus == “1”)
{
Strstatus = “Enable”;
}
else
{
Strstatus = “Disable”;
}
try
{
Stravailable_date_start = Convert.ToDateTime(DataReader[“available_date_start”].ToString()).ToString();
Stravailable_date_end = Convert.ToDateTime(DataReader[“available_date_end”].ToString()).ToString();
}
catch
{
Stravailable_date_start = “”;
Stravailable_date_end = “”;
}
dgvSub0102_01.Rows.Add(false, Strid, Struid, Strname, Strtype, Strstatus, Stravailable_date_start, Stravailable_date_end);
}
|
if-else
while (DataReader.Read())
{
Strid = DataReader[“id”].ToString();
Struid = DataReader[“uid”].ToString();
Strname = DataReader[“name”].ToString();
Strtype = DataReader[“type”].ToString();
Strstatus = DataReader[“status”].ToString();
if (Strstatus == “1”)
{
Strstatus = “Enable”;
}
else
{
Strstatus = “Disable”;
}
if ((Strname != “”) && (Strtype!=””))//try
{
Stravailable_date_start = Convert.ToDateTime(DataReader[“available_date_start”].ToString()).ToString();
Stravailable_date_end = Convert.ToDateTime(DataReader[“available_date_end”].ToString()).ToString();
}
else//catch
{
Stravailable_date_start = “”;
Stravailable_date_end = “”;
}
dgvSub0102_01.Rows.Add(false, Strid, Struid, Strname, Strtype, Strstatus, Stravailable_date_start, Stravailable_date_end);
}
|
一個800次的迴圈try-catch版總共要8秒,而if-else只要80ms,所以在迴圈之中一定不能用try-catch