Try Catch Block是否會影響效能?

跟網友在部落格上討論效能時提到一個議題--在迴圈中加入try...catch是否會影響效能?

依我的認知,try...catch只有在發生Exception時才會嚴重危害效能,平時正常執行時,我們倒可以"幾乎忘了它的存在"。

不過,我過去似乎還真沒用測試驗證過這一點,既然聊到了,就順手寫幾行Code實測一番:

using System;
using System.Diagnostics;
 
namespace TryCatchCost
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            int RUN_COUNT = 200 * 10000;
            long sum = 0;
            bool flag10K = false;
            //Test 1, no try catch
            sw.Start();
            for (int i = 0; i < RUN_COUNT; i++)
            {
                sum += i;
                if (i == 10000) flag10K = true;
            }
            sw.Stop();
            Console.WriteLine("Test1 Sum={0:N0} Time={1:N0}ms",
                sum, sw.ElapsedMilliseconds);
            //Test 2, try catch
            sw.Reset(); sum = 0;
            sw.Start();
            for (int i = 0; i < RUN_COUNT; i++)
            {
                try
                {
                    sum += i;
                    if (i == 10000) flag10K = true;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}", e.Message);
                }
            }
            sw.Stop();
            Console.WriteLine("Test2 Sum={0:N0} Time={1:N0}ms",
                sum, sw.ElapsedMilliseconds);
            //Test 3, try catch and one exception
            sw.Reset(); sum = 0;
            sw.Start();
            for (int i = 0; i < RUN_COUNT; i++)
            {
                try
                {
                    sum += i;
                    if (i == 10000)
                        throw new ApplicationException("10K");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}", e.Message);
                }
            }
            sw.Stop();
            Console.WriteLine("Test3 Sum={0:N0} Time={1:N0}ms",
                sum, sw.ElapsedMilliseconds);
 
            Console.Read();
        }
    }
}

Test1, 2, 3都分別執行200萬次的統計加總,Test2與Test1差別在於Test2中加入try catch,但完全不觸發catch段的流程;Test3則故意觸發一次Exception。為了公平起見,三個測試都加入一列if (i == 10000)。測試數據如下:

Test1 Sum=1,999,999,000,000 Time=17ms
Test2 Sum=1,999,999,000,000 Time=18ms
Error: 10K
Test3 Sum=1,999,999,000,000 Time=46ms

Test1與Test2的執行時間相同,應可推論加入try…catch不影響效能。而即使200萬次只觸發1次例外,Test3的執行時間比Test1, 2慢了一倍以上。算是驗證了推論---try…catch只有在發生Exception時才會影響效能,請安心使用

Published 20 December 2009 04:37 PM 由 Jeffrey
Filed under: ,


意見

# rico said on 20 December, 2009 08:28 AM

感謝黑暗大花時間測試,現在開始我會忘了它存在(好比夜用型...XD)~~感恩~~^^

# Slime Meteor said on 23 December, 2009 12:14 AM

找到有趣的實驗 :

Performance implications of Exceptions in .NET

www.codeproject.com/.../ExceptionPerformance.aspx

另外 MSDN 的說法是 :

"  you only incur the cost when the actual exception is thrown "

msdn.microsoft.com/.../ms973839.aspx

你的看法呢?

(必要的) 
(必要的) 
(選擇性的)
(必要的) 

請輸入以上的數字:

搜尋

Go

<December 2009>
SunMonTueWedThuFriSat
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789
 
RSS
【工商服務】
最新回應

Tags 分類檢視
關於作者

一個醉心技術又酷愛分享的Coding魔人,十年的IT職場生涯,寫過系統、管過專案, 也帶過團隊,最後還是無怨無悔地選擇了技術鑽研這條路,近年來則以做一個"有為的中年人"自許。

文章典藏
其他功能

這個部落格


BlogLook Score and Rank

Syndication