String concatenation is a very common operation to be done. From my time with Java, I have been warned many times that naive string concatenation could destroy the performance of your application. This is because the system has to create a lot of in-between strings, causing many copy operations to be executed. Instead you should use the provided StringBuilder.
Now that I came across a similar situation in C++, I was wondering whether the same is true here. In this blog post I will compare three different ways to concatenate a string. But I will go the extra mile as well, and see how combining strings and numbers has an effect on the concatenation.
The methods to create a concatenated string I will test are the following:
- The naive + operation
- The naive += operation
- A StringStream
Sprintf and StringStream can handle direct integer and double values, for the native addition, these values need to be converted to a string first. This is done using the std::to_string() method. The tested scenario’s are:
- Concatenating 5 single letter strings
- Concatenating 100 single letter strings.
- Concatenating 50 single letter strings with 50 integers (alternating)
- Concatenating 50 single letter strings with 50 doubles (alternating)
The results are mixed, as you can clearly see on the graph below.
As expected concatenating a few strings doesn’t make a big difference. Doing the same for a lot more does show a big hit for both the StringStream and the sprintf methods. But when combining strings and integers the native addition struggles. The same is true for doubles, but for some reason the StringStream can handle integers efficiently, but not doubles.
Sprintf handles integers and double very well with only a small difference in performance to the scenario with only strings. The StringStream chokes on the doubles even though it handled the integers very nicely. Note that the format in which the StringStream prints the doubles differ from the test, as it cuts off based on precision where the others have a fixed amount of digits that are being printed.
There are a couple of side remarks to be made involving usability. The sprintf method works with c style char arrays, and thus forces you to convert an actual string to and from the c style format. The native + operators only work on strings, and thus you have to do the conversion from numbers yourself. This might be a reason why they perform badly with integers and doubles, but this is something I will investigate in a next blog post. Stringstream does not have any of these downsides and is in my opinion the nicest one to use.