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.
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.)