I have read some related questions, but nothing about speed comparison between memcpy
and strncpy
.
What do you recommend to keep track of a string content within a critical section?
- avoid dynamic memory allocation
- elegance of code and readable/understandable (few code lines)
- fast processing (few instructions, prevent branch-miss)
- able to be optimized by compiler (or having implementations already using optimized instructions)
I was thinking about c functions:
memcpy
requires to calculate the min length (see snippet on coliru.stacked-crooked.com)void copy (char dst[20], const std::string& src) { if (src.size() < sizeof(dst)) { memcpy (dst, src.c_str(), src.size()+1); } else { memcpy (dst, src.data(), sizeof(dst)-1); dst[sizeof(dst)-1] = 0; } }
strncpy
searches terminating null byte and unnecessary fills all final bytes (see snippet)void copy (const std::string src, char (*dst)[20]) { strncpy (dst, src.c_str(), sizeof(dst)-1); dst[sizeof(dst)-1] = 0; }
std::string::copy
as suggested by dyp's comment...any other idea?
Benchmarks could be performed but it should be based on several compilers/versions, different flag sets and different hardware/OS. I would prefer answers based on your feedback/background/expertise or on mathematical knowledge...
As this is a general question, people searching for the same related questions will appreciate a general answer, not my own specific current case.
For your information, one thread requires to write within a file some std::string
that their content can be changed by another thread. I cannot change this other thread, and this other thread is very busy. If I do not lock (mutex/spinlock) the string copy, I have sometimes some issues. Therefore I want to quickly copy these std::string
and write them after the lock section.