C# 中的异常有多昂贵? [英] How expensive are exceptions in C#?

查看:26
本文介绍了C# 中的异常有多昂贵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 中的异常有多昂贵?只要堆栈不深,它们似乎并不昂贵;但是我读过相互矛盾的报告.

How expensive are exceptions in C#? It seems like they are not incredibly expensive as long as the stack is not deep; however I have read conflicting reports.

是否有没有被反驳的最终报告?

Is there definitive report that hasn't been rebutted?

推荐答案

在了解到异常在性能方面代价高昂后,我编写了一个简单的测量程序,与 Jon Skeet 多年前发布.我在这里提到这个主要是为了提供更新的数字.

Having read that exceptions are costly in terms of performance I threw together a simple measurement program, very similar to the one Jon Skeet published years ago. I mention this here mainly to provide updated numbers.

程序在 29914 毫秒内处理了 100 万个异常,相当于 每毫秒 33 个异常.这足以使异常成为大多数情况下返回代码的可行替代方案.

It took the program below 29914 milliseconds to process one million exceptions, which amounts to 33 exceptions per millisecond. That is fast enough to make exceptions a viable alternative to return codes for most situations.

但请注意,使用返回码而不是异常,同一程序的运行时间不到一毫秒,这意味着异常至少比返回码慢 30,000 倍.正如 Rico Mariani 所强调的,这些数字也是最少数量.在实践中,抛出和捕获异常会花费更多时间.

Please note, though, that with return codes instead of exceptions the same program runs less than one millisecond, which means exceptions are at least 30,000 times slower than return codes. As stressed by Rico Mariani these numbers are also minimum numbers. In practice, throwing and catching an exception will take more time.

在配备 Intel Core2 Duo T8100 @ 2,1 GHz 和 .NET 4.0 的笔记本电脑上测得 不在调试器下运行(这会使其变慢).

Measured on a laptop with Intel Core2 Duo T8100 @ 2,1 GHz with .NET 4.0 in release build not run under debugger (which would make it way slower).

这是我的测试代码:

static void Main(string[] args)
{
    int iterations = 1000000;
    Console.WriteLine("Starting " + iterations.ToString() + " iterations...
");

    var stopwatch = new Stopwatch();

    // Test exceptions
    stopwatch.Reset();
    stopwatch.Start();
    for (int i = 1; i <= iterations; i++)
    {
        try
        {
            TestExceptions();
        }
        catch (Exception)
        {
            // Do nothing
        }
    }
    stopwatch.Stop();
    Console.WriteLine("Exceptions: " + stopwatch.ElapsedMilliseconds.ToString() + " ms");

    // Test return codes
    stopwatch.Reset();
    stopwatch.Start();
    int retcode;
    for (int i = 1; i <= iterations; i++)
    {
        retcode = TestReturnCodes();
        if (retcode == 1)
        {
            // Do nothing
        }
    }
    stopwatch.Stop();
    Console.WriteLine("Return codes: " + stopwatch.ElapsedMilliseconds.ToString() + " ms");

    Console.WriteLine("
Finished.");
    Console.ReadKey();
}

static void TestExceptions()
{
    throw new Exception("Failed");
}

static int TestReturnCodes()
{
    return 1;
}

这篇关于C# 中的异常有多昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆