C ++ function performance issue

I ran into a C ++ function performance issue while testing the code below. The implementations of queryInterface and queryInterface1 almost the same. The only difference is that queryInterface calls the function classType and classType that calls classType1 , queryInterface1 calls classType1 directly. The performance of queryInterface1 poor; it takes twice as much as queryInterface . What is queryInterface1 problem, and why? Compiled with MSVC. See Console Output:

time value of requestInterface (): 2453

time value of requestInterface1 (): 4961

 #include <string> #include <time.h> #include <iostream> #include <unordered_map> using namespace std; namespace { int find(const string& name) { return 0; } class A { public: static int classType(); static int classType1(); virtual void* queryInterface(int id) const { if (A::classType() == id) return const_cast<A*>(this); return nullptr; } virtual void* queryInterface1(int id) const { if (A::classType1() == id) return const_cast<A*>(this); return nullptr; } }; int A::classType() { static int s_classType = classType1(); return s_classType; } int A::classType1() { static int s_classType = find("A"); return s_classType; } } int main() { clock_t start, stop; const size_t count = 1000000000; A* pA = new A; start = clock(); for (size_t i = 0; i < count; i++) { pA->queryInterface(A::classType()); } stop = clock(); cout << "time cost of queryInterface(): " << stop - start << endl; start = clock(); for (size_t i = 0; i < count; i++) { pA->queryInterface1(A::classType1()); } stop = clock(); cout << "time cost of queryInterface1(): " << stop - start << endl; return 0; } 
+5
source share
1 answer

The difference in performance is due to the fact that the compiler sets up security checks as part of the A::classType1 . These settings are configured for each call, even if it is really only necessary when the find function is called.

Security checks determine whether the stack has been overwritten, potentially knocking out the stack frame, including the return address.

Changing the initial value if s_classType is a constant integer, instead of calling find leads to significantly faster calls to queryInterface1 .

Security checks can be disabled using the /GS- compiler option.

+4
source

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


All Articles