Performance Cost Of 'try' in C#

前端 未结 5 1271
名媛妹妹
名媛妹妹 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:27

    Actually, a couple months ago I was creating an ASP.NET web app, and I accidentally wrapped a try / catch block with a very long loop. Even though the loop wasn't generating every exceptions, it was taking too much time to finish. When I went back and saw the try / catch wrapped by the loop, I did it the other way around, I wrapped the loop IN the try / catch block. Performance improved a LOT. You can try this on your own: do something like

    int total;
    
    DateTime startTime = DateTime.Now;
    
    for(int i = 0; i < 20000; i++)
    {
    try
    {
    total += i;
    }
    catch
    {
    // nothing to catch;
    }
    }
    
    Console.Write((DateTime.Now - startTime).ToString());
    

    And then take out the try / catch block. You'll see a big difference!

提交回复
热议问题