Why does an unreachable try-catch block increase execution time?

I am currently creating my own Lib container, but I saw that this unreachable (invalid if statement) try-catch blocked the increase in runtime. 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 10,000,000 and Type is int.

reserve function acts as in std .

Timer is a small library that I created to easily measure time, overloading std::chrono .

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

So, I want to know why this try-catch increases the time without reaching ( _capacity is equal to _size only after the last click). Does the compiler (MSVC 2017) represent a try-catch block on the stack, even if it is not in use?

NB: if you want a Visual Studio 2017 solution, I can send it to you.

+2
source share
1 answer

When you add try / catch , the compiler adds code to support exceptions. This is done in the function header (along with code for allocating space for local variables and saving registers). With MSVC, part of the exception support that is performed consists of setting a global variable that points to the local data of the exception, storing the previous value of this pointer, initializing the local variable, indicating which try / catch block in the active function, and setting up another local variable that points to the table of exception handlers .

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

Other compilers may have different ways of handling exceptions.

+1
source

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


All Articles