加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 04:57:45 所属栏目:百科 来源:网络整理
导读:用于澄清代码边界的大括号范围是否会增加代码执行时间?在我看来,确实如此.因为在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),使用和不使用大括号并比较结果来确认这一点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读