用于评论目的的大括号范围是否会降低C代码的速度?

用于澄清代码边界的大括号范围是否会增加代码执行时间?在我看来,确实如此.因为在C中退出花括号范围意味着堆栈展开和用于注释目的的花括号范围会增加堆栈展开时间.但我不知道是否昂贵?我可以忽略副作用吗?

除了以下代码片段的代码本身之外,您应该专注于代码结构.

#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";
}
退出范围会破坏在该范围内声明的所有局部变量(最小的第一个).在您的示例中,范围中没有声明局部变量,因此不应该有开销.在这种情况下,您可以通过编译汇编语言(gs下的-s),使用和不使用大括号并比较结果来确认这一点.
本站公众号
   欢迎关注本站公众号,获取更多程序园信息
开发小院