我问了一个关于 exceptions的问题,我对那些说投掷很慢的人非常恼火.我在 How exceptions work behind the scenes过去问过,我知道在正常的代码路径中没有额外的指令(正如接受的答案所说)但我并不
{
int ret = func();
if (ret == 1)
return;
if (ret == 2)
return;
doSomething();
}
VS
{
try{
func();
doSomething();
}
catch (SpecificException1 e)
{
}
catch (SpecificException2 e)
{
}
}
据我所知,除了ifs被移出正常的代码路径进入异常路径和一个额外的跳转或两个到达异常代码路径之外没有区别.当它减少主要且经常运行的代码路径中的几个ifs时,额外的跳跃或两个听起来并不多.那些异常实际上是慢的吗?或者这是旧编译器的神话还是旧问题?
(我在谈论一般的例外.具体来说,编译语言中的例外情况,比如C和D;虽然C#也在我的脑海里.)
好的 – 我只是进行了一些测试,以确保异常实际上更慢.简介:在我的机器上,每次迭代调用w / return是30个循环.每次迭代抛出w / catch为20370个循环.所以回答这个问题 – 是的 – 抛出异常很慢.
这是测试代码:
#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);
}
另一种尝试/捕获由op编写
try
{
if(Test1()!=0)
result++;
}
catch(int x)
{
result++;
