Why are try blocks expensive?

前端 未结 11 2435
醉酒成梦
醉酒成梦 2020-12-02 13:13

I\'ve heard the advice that you should avoid try catch blocks if possible since they\'re expensive.

My question is specifically about the .NET platform: Why are try

11条回答
  •  执笔经年
    2020-12-02 13:50

    I think people really overestimate the performance cost of throwing exceptions. Yes, there's a performance hit, but it's relatively tiny.

    I ran the following test, throwing and catching a million exceptions. It took about 20 seconds on my Intel Core 2 Duo, 2.8 GHz. That's about 50K exceptions a second. If you're throwing even a small fraction of that, you've got some architecture problems.

    Here's my code:

    using System;
    using System.Diagnostics;
    
    namespace Test
    {
        class Program
        {
            static void Main(string[] args)
            {
                Stopwatch sw = Stopwatch.StartNew();
                for (int i = 0; i < 1000000; i++)
                {
                    try
                    {
                        throw new Exception();
                    }
                    catch {}
                }
                Console.WriteLine(sw.ElapsedMilliseconds);
                Console.Read();
            }
        }
    }
    

提交回复
热议问题