根據上篇

如果我們可以用 try..catch 來解決 int.Parse 出現的exception 問題, 那為何需要用 int.TryParse ?

答案是"效能"!

底下範例使用 Stopwatch 來測試 Parse 跟 TryParse 的效能


Sample:

int iNum;

Stopwatch sw = null;
long ticks;

// int.Parse Success
sw = Stopwatch.StartNew();
for (int i = 1; i < 1000; i++)
{
try
{
iNum = int.Parse("123");
}
catch (Exception)
{
iNum = 0;
}
}
sw.Stop();
ticks = sw.ElapsedTicks; // Total Ticks
Response.Write("int.Parse() : Success, Total " + ticks + " ticks
");

// int.TryParse Success
sw = Stopwatch.StartNew();
for (int i = 1; i < 1000; i++)
{
if (!int.TryParse("123", out iNum))
{
iNum = 0;
}
}
sw.Stop();
ticks = sw.ElapsedTicks; // Total Ticks
Response.Write("int.TryParse() : Success, Total " + ticks + " ticks
");

// int.TryParse Fail
sw = Stopwatch.StartNew();
for (int i = 1; i < 1000; i++)
{
try
{
iNum = int.Parse("abc");
}
catch (Exception)
{
iNum = 0;
}
}
sw.Stop();
ticks = sw.ElapsedTicks; // Total Ticks
Response.Write("int.Parse() : Fail, Total " + ticks + " ticks
");

// int.TryParse Fail
sw = Stopwatch.StartNew();
for (int i = 1; i < 1000; i++)
{
if (!int.TryParse("abc", out iNum))
{
iNum = 0;
}
}
sw.Stop();
ticks = sw.ElapsedTicks; // Total Ticks
Response.Write("int.TryParse() : Fail, Total " + ticks + " ticks
");


Output:

int.Parse() : Success, Total 971 ticks
int.TryParse() : Success, Total 944 ticks
int.Parse() : Fail, Total 481736 ticks
int.TryParse() : Fail, Total font color="green">822 ticks

數據上看來, 兩種方式在發生exception時, 處理的時間竟然差了幾百倍
除非程式不會出現Exception (??), 否則應該要使用TryParse, 程式碼也較精簡.
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 nengchung 的頭像
    nengchung

    崇言崇語

    nengchung 發表在 痞客邦 留言(1) 人氣()