Does curly brace affect commenting goals to slow down C ++ code?

Does the area increase the curly bracket to clarify the code boundary? In my opinion, this is so. Because exiting the curly brace in C ++ means unwinding the stack and the curly brace for comment purposes increases the unwinding of the stack . But I have no idea whether it is expensive or not? Can I ignore the side effect?

You should focus on the code line different from the code of the next code fragment itself.

#include <iostream>
#include <utility>
#include <vector>
#include <string>

int main()
{
    std::string str = "Hello";
    std::vector<std::string> v;

    {// uses the push_back(const T&) overload, which means 
     // we'll incur the cost of copying str
        v.push_back(str);
        std::cout << "After copy, str is \"" << str << "\"\n";

        //other code involves local variable
     }

    {// uses the rvalue reference push_back(T&&) overload, 
     // which means no strings will be copied; instead, the contents
     // of str will be moved into the vector.  This is less
     // expensive, but also means str might now be empty.
        v.push_back(std::move(str));
        std::cout << "After move, str is \"" << str << "\"\n";

        //other code involves local variable
   }

    std::cout << "The contents of the vector are \"" << v[0]
                                     << "\", \"" << v[1] << "\"\n";
}
+6
source share
4 answers

, ( ). , , . , (-s gcc), .

+3

, , . , , , , . , . , .

. , , "", .

+2

, . , .

, std::string , std::vector. main, , . . , .

+1

: . ( , , !)

, , . , , , . . , : int , int, int .

So, when you reduce the scope of local variables, you allow the compiler to reuse more slots in the stack frame. This reduces the overall size of your stack and the distance that the stack grows / shrinks. This, in turn, leads to better cache utilization and therefore better performance.

However, the effect of this effect is negligible, so you should generally ignore it and just write the most readable code you can.

+1
source

All Articles