1

The function gets called very frequently, so I try to lower memory-reallocation etc. What bothers me, is the vector and int, though I cant move them outside the function otherwise I get std::bad_alloc. So far I have:

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) 
}
droid192
  • 2,011
  • 26
  • 43
  • 2
    You needn't worry about the int, there is no real allocation for it. Besides, the vector, string and stringstream objects are going to be far more heavy-weight. – Michael Albers Feb 14 '16 at 21:29

1 Answers1

1

Have you profiled the application? and is that your code REALLY the bottle neck? If you have... then

Well, if you are using a C++11 compiler you could do this, if you don't have a C++11 compiler, remove the thread_local but then you'll have to take care of reentrancy if there is a chance that that routine will be called in a multithreaded code

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) 
}

cbstrVec and str will have their memory reused since cbstrVec.clear() doesn't really deallocate all the memory allocated by the vector and reassigning str will reuse the internal storage in a good STL implementation

Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68