c# - 当不抛出异常时,try/catch block 会影响性能吗?

标签 c# performance try-catch

在与 Microsoft 员工进行代码审查时,我们发现 try{} block 中有一大段代码。她和一位 IT 代表建议这可能会影响代码的性能。事实上,他们建议大部分代码应该在 try/catch block 之外,并且应该只检查重要的部分。微软员工补充说,即将发布的白皮书警告不要使用不正确的 try/catch block 。

我环顾四周,找到了它 can affect optimizations , 但它似乎只适用于范围之间共享变量的情况。

我不是在问代码的可维护性,甚至不是在处理正确的异常(毫无疑问,有问题的代码需要重构)。我也不是指使用异常进行流量控制,这在大多数情况下显然是错误的。这些都是重要的问题(有些更重要),但不是这里的重点。

抛出异常时,try/catch block 如何影响性能?

最佳答案

检查它。

static public void Main(string[] args)
{
    Stopwatch w = new Stopwatch();
    double d = 0;

    w.Start();

    for (int i = 0; i < 10000000; i++)
    {
        try
        {
            d = Math.Sin(1);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

    w.Stop();
    Console.WriteLine(w.Elapsed);
    w.Reset();
    w.Start();

    for (int i = 0; i < 10000000; i++)
    {
        d = Math.Sin(1);
    }

    w.Stop();
    Console.WriteLine(w.Elapsed);
}

输出:

00:00:00.4269033  // with try/catch
00:00:00.4260383  // without.

以毫秒为单位:

449
416

新代码:

for (int j = 0; j < 10; j++)
{
    Stopwatch w = new Stopwatch();
    double d = 0;
    w.Start();

    for (int i = 0; i < 10000000; i++)
    {
        try
        {
            d = Math.Sin(d);
        }

        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        finally
        {
            d = Math.Sin(d);
        }
    }

    w.Stop();
    Console.Write("   try/catch/finally: ");
    Console.WriteLine(w.ElapsedMilliseconds);
    w.Reset();
    d = 0;
    w.Start();

    for (int i = 0; i < 10000000; i++)
    {
        d = Math.Sin(d);
        d = Math.Sin(d);
    }

    w.Stop();
    Console.Write("No try/catch/finally: ");
    Console.WriteLine(w.ElapsedMilliseconds);
    Console.WriteLine();
}

新结果:

   try/catch/finally: 382
No try/catch/finally: 332

   try/catch/finally: 375
No try/catch/finally: 332

   try/catch/finally: 376
No try/catch/finally: 333

   try/catch/finally: 375
No try/catch/finally: 330

   try/catch/finally: 373
No try/catch/finally: 329

   try/catch/finally: 373
No try/catch/finally: 330

   try/catch/finally: 373
No try/catch/finally: 352

   try/catch/finally: 374
No try/catch/finally: 331

   try/catch/finally: 380
No try/catch/finally: 329

   try/catch/finally: 374
No try/catch/finally: 334

关于c# - 当不抛出异常时,try/catch block 会影响性能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1308432/

相关文章:

scala - 在Scala中正确使用Either、Try和Exceptions/ControlThrowable

java - 阻止 ArrayOutOfBoundsException 在 Java 中停止程序执行

c# - 关于在 C# 中制作可重用的 try/catch block 的建议?

c# - SQL Server 2005 比较日期

c# - Xamarin 中的异步按钮事件

performance - 使用 simd 指令时,32 位图像处理是否比 24 位图像处理更快?

c++ - C++中的复杂内存管理问题

c# - 当无法到达取消 token 时,如何中止或终止 TPL 任务?

c# - 如何以编程方式将数据添加到 WPF 数据网格

mysql - MBR包含距离位置帮助MySQL