c++ - 避免在给定示例上重新分配内存

标签 c++ optimization allocation ros

该函数被频繁调用,所以我尝试降低内存重新分配等。令我困扰的是 vectorint,尽管我不能将它们移到外面函数否则我得到 std::bad_alloc。到目前为止,我有:

void callbString(const std_msgs::String::ConstPtr& msg)
{
    vector<string> cbstrVec;
    int cbtype;

    //get string and split into vector
    string str = (msg->data.c_str());
    if(str.empty()) return;
    str.erase(0,1);
    boost::split(cbstrVec, str, boost::is_any_of(" "));
    stringstream(cbstrVec[2])>>cbtype;
    c.setvec(cbstrVec,cbtype); //takes (vector<string>,int) 
}

最佳答案

您是否对应用程序进行了概要分析?你的代码真的是瓶颈吗?如果你有...那么

好吧,如果你使用的是 C++11 编译器,你可以这样做,如果你没有 C++11 编译器,请删除 thread_local 但是你将不得不照顾好reentrancy如果有可能在多线程代码中调用该例程

void callbString(const std_msgs::String::ConstPtr& msg)
{
    static thread_local vector<string> cbstrVec;
    static thread_local std::string str;

    int cbtype;  //int is super cheap

    cbstrVec.clear();

    //get string and split into vector
    str = (msg->data.c_str());
    if(str.empty()) return;
    str.erase(0,1);
    boost::split(cbstrVec, str, boost::is_any_of(" "));
    stringstream(cbstrVec[2])>>cbtype;
    //c.setvec(cbstrVec,cbtype); //takes (vector<string>,int) 
    c.setvec(std::move(cbstrVec),cbtype); //takes (vector<string>,int) 
}

cbstrVecstr 将重用它们的内存,因为 cbstrVec.clear() 并没有真正释放 vector 分配的所有内存并重新分配 str 将在良好的 STL 实现中重用内部存储

关于c++ - 避免在给定示例上重新分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35398170/

相关文章:

c++ - 是否可以缓存从 MapViewOfFile 返回的映射区域?

c++ - 编译错误 : library not found

c++ - 并行数组以创建数据库来存储C++的动物类型和数量

c++ - 访问指向结构中的值是否比访问本地值花费更多时间?

c - 为什么这段代码不在 C 中分配内存?

c++ - 返回值(引用、指针和对象)

algorithm - 粒子/遗传群优化算法中的粒子(代码方面)是什么?

python - 使用cython性能下降

c - 函数在 Release模式下崩溃,但在调试器中运行完美

arrays - Julia - 许多分配以浏览结构中的数组