I am trying to efficiently convert the contents of a map to a string to send via socket. I have this so far...
char buffer[1024];
for (iter = my_mapy.begin(); iter != my_map.end();iter++)
{
sprintf(buffer, "%s|%ld|%d", buffer, iter->first, iter->second);
}
While this is working, I was wondering whether it is inefficient. Google searches for the most efficient way to convert int/long/doubles to string resulted in sprintf, which is why I am using it. But I am worried that the contents of buffer are getting copied over and over, whereas I just want to append to the end. Is this correct, and if so, is there a better way to do this? Performance and speed is #1 priority.
Thanks!
You're correct; the solution you proposed here will copy the buffer every time. To do better, you will have to make use of the return value of sprintf.
char buffer[1024];
char* end_of_buffer = buffer;
std::size_t remaining_space = sizeof(buffer);
for (auto iter = my_map.begin(); iter != my_map.end(); iter++)
{
int written_bytes = snprintf(end_of_buffer, remaining_space, "|%ld|%d", iter->first, iter->second);
if (written_bytes > 0) {
end_of_buffer += written_bytes;
remaining_space -= written_bytes;
} else {
perror("Something is wrong with the buffer");
}
}
Notice, by the way, that I used snprintf
, which keeps track of the buffer's remaining length. You should always use this instead of the unsafe version. Your application will evolve, and through great creativity you will find a way to overflow this buffer. Meanwhile the safety comes at zero additional cost.
(I mean no offense, of course.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With