First of all, I cannot tell which version is faster. It highly depends on your compiler, system, implementation, etc, as you probably knows.
If you know the size in advance (you have an std::string
and size()
takes O(1)
), it is probably faster to use memcpy
as it has less things to do (just copies, no comparisons). You can write it this way:
void copy(char* buffer, std::size_t buffersize, const std::string& str)
{
std::size_t len = std::min(buffersize-1, str.size());
memcpy(buffer, &str[0], len); // using &str[0] instead of data()
buffer[len] = '\0';
}
But I wouldn't take the word of anyone on that. The right thing to do is test all variations you have and decide for your specific scenario (that I know nothing about).
My specific case is to store quickly some
std::string
within a critical section (spin lock) and to dump these strings after. Therefore I want to prevent dynamic memory allocation.
What I didn't understand is why don't use std::string
. If you want prevent allocations, you can reserve()
some memory to your string (the same amount you would have on the char array). Or you can take a const reference to the string and use it on the critical section. No allocation will take place.