捕捉异常时真的有一个表现吗? [英] Is there really a performance hit when catching exceptions?

查看:192
本文介绍了捕捉异常时真的有一个表现吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了关于例外情况的问题,我对人们非常恼火说投掷很慢过去我问过幕后如何例外工作我知道在正常的代码路径没有额外的指令(如接受的答案所说),但我不完全相信抛出更昂贵,然后检查返回值。请考虑以下内容:

I asked a question about exceptions and I am getting VERY annoyed at people saying throwing is slow. I asked in the past How exceptions work behind the scenes and I know in the normal code path there are no extra instructions (as the accepted answer says) but I am not entirely convinced throwing is more expensive then checking return values. Consider the following:

{
    int ret = func();
    if (ret == 1)
        return;
    if (ret == 2)
        return;
    doSomething();
}

vs

{
    try{
        func();
        doSomething();
    }
    catch (SpecificException1 e)
    {
    }
    catch (SpecificException2 e)
    {
    }
}

据我所知,除之外没有区别,如果 s被从正常的代码路径移出到一个异常路径和一个额外的跳过或两个到异常代码路径。当你的主要和更经常运行的代码路径减少一些,如果 s减少了一个额外的跳跃或两个听起来不会太多。那么例外实际上是慢吗?或者这是旧的编译器的神话或旧问题?

As far as I know there isn't a difference except the ifs are moved out of the normal code path into an exception path and an extra jump or two to get to the exception code path. An extra jump or two doesn't sound like much when it reduces a few ifs in your main and more often run) code path. So are exceptions actually slow? Or is this a myth or an old issue with old compilers?

(我在说一般的异常)具体来说,编译语言中的异常,如C ++和D; C#也在我心中。)

(I'm talking about exceptions in general. Specifically, exceptions in compiled languages like C++ and D; though C# was also in my mind.)

推荐答案

好吧,我刚刚运行一点测试来确保异常实际上更慢。总结:在我的机器上,每次迭代都有30个循环。每次迭代都会有20370次循环。

Okay - I just ran a little test to make sure that exceptions are actually slower. Summary: On my machine a call w/ return is 30 cycles per iteration. A throw w/ catch is 20370 cycles per iteration.

所以要回答这个问题 - 是 - 抛出异常缓慢。

So to answer the question - yes - throwing exceptions is slow.

以下是测试代码:

#include <stdio.h>
#include <intrin.h>

int Test1()
{
    throw 1;
//  return 1;
}


int main(int argc, char*argv[])
{
    int result = 0;
    __int64 time = 0xFFFFFFFF;
    for(int i=0; i<10000; i++)
    {
        __int64 start = __rdtsc();
        try
        {
            result += Test1();
        }
        catch(int x)
        {
            result += x;
        }
        __int64 end = __rdtsc();
        if(time > end - start)
            time = end - start;
    }

    printf("%d\n", result);
    printf("time: %I64d\n", time);
}

替代try / catch由op编写

alternative try/catch written by op

try
{
        if(Test1()!=0)
                result++;
}
catch(int x)
{
        result++;

这篇关于捕捉异常时真的有一个表现吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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