Why unreached try-catch block increase Runtime time?

醉酒当歌 提交于 2019-12-24 04:37:07

问题


I'm currently creating my own container Lib, but I've seen that unreachable(invalidated if statement) try-catch block increased runtime time. So here is my test,

Vector.cpp :

template<class Type, class Allocator >
void vector<Type, Allocator >::push_back(Type&& ObjectToPushBack)
{
    if (_capacity == _size)
    {
#if 1
        try
        {
            emplace_back(std::move(ObjectToPushBack));
        }
        catch (NullException& n)
        {
            std::cout << n.what() << std::endl;
            throw n;
        }
#endif
    }
    else
        emplace_back_no_except(std::move(ObjectToPushBack));
}  

Main.cpp :

int _cdecl main()
{
    ctn::vector<TYPE> myvec;

    Timer t;

    myvec.reserve(NB);

    auto f = [&]() {for (int i = 0; i < NB; ++i)myvec.push_back(TYPE());};

    t.timeThisFunction(f, ("My Vector Push Back " + std::to_string(NB) + " 
    Elements").c_str());
}

NB is 10000000 and Type is int.

reserve function act like the in the std.

Timer is a little lib that I've created to measure time easily , it overload std::chrono.

The average time with the try-catch block is ~70ms and with the block commented, ~18ms, this is a big gap between the two.

So, I want to know why this try-catch block increase the time without being reached( the _capacity equal the _size only after the final push), Is the compilator(MSVC 2017) pre-allocate try-catch block on the stack, even if unused ?

NB : if you want the Visual Studio 2017 Solution, i can send it to you.


回答1:


When you add in a try/catch block, the compiler adds in code to support exceptions. This is executed in the function header (along with the code to allocate space for local variables and save registers). With MSVC, some of the exception support that is executed appears to consist of setting a global variable to point to the local exception data, saving the previous value of this pointer, initializing a local variable to indicate which try/catch block in the function is active, and setting up another local variable that points to a table of exception handlers.

The active index is updated whenever a try block is entered or exited.

Other compilers can have different ways to handle exceptions.



来源:https://stackoverflow.com/questions/47244407/why-unreached-try-catch-block-increase-runtime-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!