I have a program where I need to generate and send a string if an event occurs.
My initial code was something like:
1 2 3 4 5 6 7 8 9 10 11 12 13
std::string label = "some constant text"
...
std::string message = "Event detected by " + label;
// an event has an integer that increments and a const char*
message = message + ", :" + std::to_string(event_number) + "\t" + std::string(event_source);
... open a socket
BytesSent = send(SendingSocket, message.c_str(), strlen(message.c_str()), 0);
... close socket
As you can see initially I was not very concerned about performance and opted to bring everything to std::string and concatenate those. It turns out the events are rather frequent and as a result I am doing this very often, what leads to high CPU usage. So now I would like to try to lower the CPU usage by making this more efficient.
The first thing I changed was to open the socket and keep the connection for the next message. But now I would like to improve the efficiency of the message generation and I would like to ask for your advice on how to best do this.
I could stick with the std::string, but I could go to std::stringstream, I could use a char buffer instead of a std::string, of implement something like sprintf and probably there are even more alternatives possible. [strong]The main question is, what would be the most efficient way and why?[/strong]
> It turns out the events are rather frequent and as a result I am doing this very often, what leads to high CPU usage.
> So now I would like to try to lower the CPU usage by making this more efficient.
It is extremely unlikely that formatting the messages is what is taking a significant portion of cpu time.
As far as performance goes, one measurement is worth more than a thousand opinions.
Measure the time taken to format messages on your implementation; consider low-level optimisation if and only if it turns out to be a bottleneck.