try catch performance

前端 未结 7 958
小蘑菇
小蘑菇 2020-11-29 09:28

This article on MSDN states that you can use as many try catch blocks as you want and not incur any performance cost as long no actual exception is thrown.
Since I alway

7条回答
  •  萌比男神i
    2020-11-29 09:47

    The Problem is first at your Test Code. you used stopwatch.Elapsed.Milliseconds which shows only the milisecond part of the Elapsed time, use TotalMilliseconds to get the whole part...

    If no exception is thrown, the difference is minimal

    But the real question is "Do i need to check for exceptions or let C# handle the Exception throwing?"

    Clearly... handle alone... Try running this:

    private void TryCatchPerformance()
        {
            int iterations = 10000;
            textBox1.Text = "";
            Stopwatch stopwatch = Stopwatch.StartNew();
            int c = 0;
            for (int i = 0; i < iterations; i++)
            {
                try
                {   
                    c += i / (i % 50);
                }
                catch (Exception)
                {
    
                }
            }
            stopwatch.Stop();
            Debug.WriteLine(String.Format("With try catch: {0}", stopwatch.Elapsed.TotalSeconds));
    
            Stopwatch stopwatch2 = Stopwatch.StartNew();
            int c2 = 0;
            for (int i = 0; i < iterations; i++)
            {
                int iMod50 = (i%50);
                if(iMod50 > 0)
                    c2 += i / iMod50;
            }
            stopwatch2.Stop();
            Debug.WriteLine( String.Format("Without try catch: {0}", stopwatch2.Elapsed.TotalSeconds));
    
        }
    

    Output: OBSOLETE : Look below! With try catch: 1.9938401

    Without try catch: 8.92E-05

    Amazing, only 10000 objects, with 200 Exceptions.

    CORRECTION: I Run my code on DEBUG and VS Written Exception to Output window.. These are the Results of the RELEASE A lot less overhead, but still 7,500 % improvement.

    With try catch: 0.0546915

    Checking Alone: 0.0007294

    With try catch Throwing my own same Exception object: 0.0265229

提交回复
热议问题