skip to Main Content

I have a large char* in shared-memory, I want to copy it to a string, but I don’t want to add extra copy or init. theoretically once copy is enough.

My code like this

//params must be a string, because parent need. If params changed, I need copy other struct -> std::string. 
void Read(string *str) {
  size_t len;
  shm.ReadLen(len);
  str->resize(len); //malloc once and init once.
  shm.ReadStr(&((*str)[0]), len);//copy once
}

My ideal code is

void Read(string* str) {
  size_t len;
  shm.ReadLen(len);
  str->reserve(len);//malloc once 
  shm.ReadStr(&((*str)[0]), len); //copy once 
  str.set_size(len);//???
}

my question: string.resize() is too slow, a half costs in my Read function.

shm.ReadStr(char* dest, size_t len) {
    memcpy(dest, shm_src, len);
}

ReadStr function is belong to my colleague. I don’t want to change it, but I can change it, if necessary.

my system: gcc 5.3.0 in centos.

3

Answers


  1. The fastest is

    shm.ReadStr(std::string& str, size_t len) {
        str.assign(shm_src, len);
    }
    

    Don’t care of resize, std::string will do it the best.

    Login or Signup to reply.
  2. The best is to use string::assign, if shared memory interface allows it.

    Otherwise, there is no portable ways to do, but some libraries allow this. E.g. Facebook’s folly library and Google’s absl support uninitiated resize (when working on supported compiler and platform – they have to rely on nonportable hacks).

    Login or Signup to reply.
  3. if your data is already in memory, and you don’t want to copy it, but want to manipulate it as a string-like object, try using std:string_view();
    that would be the fastest, since no copy is necessary.

    std::string_view ReadStr(size_t len) {
      return string_view(shm_src, len);
    }
    
    std::string_view sv = ReadStr(len); // zero-copy access to data
    std::string s = sv; // have a copy now, if you need it
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search