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
The fastest is
Don’t care of resize, std::string will do it the best.
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).
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.