简体   繁体   English

在没有命中时,C ++中的try catch是否会影响性能

[英]Does try catch in C++ affect performance when not hit

I have code where there is a try catch in a function and the function gets hit. 我有代码,其中函数中有try catch,函数被命中。 100+ times. 100次以上。 The code return early everytime without actually hitting the try catch. 代码每次都会提前返回,而不会实际触及try catch。 Does this affect performance in Visual Studio. 这是否会影响Visual Studio的性能。 I am seeing a performance impact. 我看到了性能影响。

My code was : 我的代码是:

void foo(int a) {
 if (a > value) {
    return;
 }
 try {
    possibleErrorFunction();
 } catch {
 }
}

I changed it to: 我改成了:

void foo(int a) {
if (a > value) {
    return;
}
bar();
}

void bar() {
try {
    possibleErrorFunction();
} catch {
}
}

The second code seems about 10 sec faster. 第二个代码似乎快了大约10秒。 Is there any resaonable explanation for this? 对此有任何可以解释的解释吗?

There are 2 major policies used in exception mechanism implementation. 异常机制实现中使用了两个主要策略。 One is so-called "frame based", or "dynamic" and another one is "table based". 一个是所谓的“基于帧”或“动态”,另一个是“基于表格”。 Other schemes are variations of those two. 其他方案是这两者的变体。 You can read more about them here 你可以在这里阅读更多相关信息

In essence, "frame-based" dynamic implementation does spend resources on each entry into and exit from try block at run-time. 本质上,“基于帧”的动态实现确实在运行时将每个条目的资源花费在try块上和从try块中退出。 The "table based" mechanism does not involve any extra work if exception is not thrown but it uses much more memory. 如果不抛出异常但是它使用了更多的内存,那么“基于表”的机制不涉及任何额外的工作。

I am not 100% sure but as far as I know Microsoft compiler up till VS2008 used "frame-based" approach and starting from VS2010 it implements "table-based" approach. 我不是100%肯定,但据我所知Microsoft编译直到VS2008使用“基于帧”的方法,并从VS2010开始实现“基于表”的方法。 (Maybe there are some compiler switches that can control it - I don't know because I personally prefer not to use exceptions until forced by existing code or 3rd party libraries). (也许有一些编译器开关可以控制它 - 我不知道,因为我个人不希望在现有代码或第三方库强制之前不使用异常)。 I think you can find this information in your compiler documentation. 我想你可以在编译器文档中找到这些信息。

You could also produce assembler code from your c++ source to see what is going on with your try block 您还可以从c ++源代码生成汇编代码,以查看try块的运行情况

All of the above comments seem to converge toward a useful point or two. 所有上述评论似乎都趋向于有用的一两点。 Extra apparatus always engages more CPU cycles and thus derogatively affects performance (I can't believe this editing box flagged "derogatively"). 额外的设备总是会占用更多的CPU周期,从而贬低性能(我不相信这个编辑框被标记为“贬义”)。 Many iterations over many instances are required. 需要在许多实例上进行许多迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM