Is performance really striking when catching exceptions?

I asked a question about exceptions , and I get really annoyed when people say that the throw is slow. I asked in the past How exceptions work behind the scenes , and I know that there are additional instructions in the regular code (as the accepted answer says), but I am not completely convinced that the throw is more expensive than checking the 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)
    {
    }
}

, , , if , . , , if ). ? ?

( . , , ++ D, # .)

+3
10

. , , . : w/return 30 . 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);
}

try/catch, op

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

, , , (, CLR), , .... , , ... , ( ) ..

, catch ( ) CLRs ... , catch , , , .

+5

, .

- , , . .

, , .

+3

# raise , . , . , , , .

, - , . , , , (, , , ).

, , , , . , TryParse Parse KeyExists .. 100 , .

+2

, . , , . , (, , ) .

+2

tl; dr . . .

, .

:

, ( , , - n O (n ^ 3) O (n ln n) ..).

:

+1

. ++. 8086 . CPU. , 2 , . , " " gcc ( , . .) , ( try {} catch {}.). 20% ( 20% ). 3- 4- ...

, , , .

+1

, Windows SEH, , Matt Pietrik . . , .NET, , . .

, , . , , , , .

0

, .

  • catch , . , if , .

  • - , , , . , - , - , "" , , . , . , (, EAX).

0

concinating strings vs stringbuilder. , .

-1

Source: https://habr.com/ru/post/1723470/


All Articles