Performance Cost Of 'try' in C#

前端 未结 5 1259
名媛妹妹
名媛妹妹 2020-11-28 12:38

I know that exceptions have a performance penalty, and that it\'s generally more efficient to try and avoid exceptions than to drop a big try/catch around everything -- but

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 13:10

    To see what it really costs, you can run the code below. It takes a simple two dimensional array and generates random coordinates which is out of range. If your exception only occurs one time, of course you will not notice it. My example is done to emphasize what it will mean when doing this several thousand times, and what catching an exception vs implementing a simple test will save you.

            const int size = 1000;
            const int maxSteps = 100000;
    
            var randomSeed = (int)(DateTime.UtcNow - new DateTime(1970,1,1,0,0,0).ToLocalTime()).TotalMilliseconds;
            var random = new Random(randomSeed);
            var numOutOfRange = 0;
            var grid = new int[size,size];
            var stopwatch = new Stopwatch();
            Console.WriteLine("---Start test with exception---");
            stopwatch.Reset();
            stopwatch.Start();
            for (int i = 0; i < maxSteps; i++)
            {
                int coord = random.Next(0, size * 2);
                try
                {
                    grid[coord, coord] = 1;
                }
                catch (IndexOutOfRangeException)
                {
                    numOutOfRange++;
                }
            }
            stopwatch.Stop();
            Console.WriteLine("Time used: " + stopwatch.ElapsedMilliseconds + "ms, Number out of range: " + numOutOfRange);
            Console.WriteLine("---End test with exception---");
    
            random = new Random(randomSeed);
    
            stopwatch.Reset();
            Console.WriteLine("---Start test without exception---");
            numOutOfRange = 0;
            stopwatch.Start();
            for (int i = 0; i < maxSteps; i++)
            {
                int coord = random.Next(0, size * 2);
                if (coord >= grid.GetLength(0) || coord >= grid.GetLength(1))
                {
                    numOutOfRange++;
                    continue;
                }
                grid[coord, coord] = 1;
            }
            stopwatch.Stop();
            Console.WriteLine("Time used: " + stopwatch.ElapsedMilliseconds + "ms, Number out of range: " + numOutOfRange);
            Console.WriteLine("---End test without exception---");
            Console.ReadLine();
    

    Example output of this code:

    ---Start test with exception---
    Time used: 3228ms, Number out of range: 49795
    ---End test with exception---
    ---Start test without exception---
    Time used: 3ms, Number out of range: 49795
    ---End test without exception---
    

提交回复
热议问题