It seems that std::string – because it doesn’t use expression templates – has a O(n^2) complexity instead of a possibly O(n) complexity for some operations like concatenation. Same thing with a std::stringstream class when you have to insert many elements.
I would like to understand this, at least if someone could have some good links about this point that would be great.
Concatenating multiple strings together has different complexities in C++ depending how it is done. I believe the situation that you’re thinking of is:
which concatenates 6 strings. The first string is copied 5 times, the second is copied 4 times, and so forth. As Leonid Volnitsky notes in his answer, the exact bound for this Θ(NM), where M is the number of concatenation operations, and N is the total length of the strings being concatenated. We can also call this O(N^2) when M <= N. Note that it’s not guaranteed that M <= N, because you can increase M without increasing N by trying to concatenate the empty string.
Expression templates could help speed up this use case, though it would cause problems with
autoanddecltypetype inference in C++11, as well as with template type inference in C++98. All of these would deduce the type ofto be the lazily-evaluated string template type that was used to make the expression template magic happen. Other reasons why expression templates are not a great idea include Leonid Volnitsky‘s answer about this slowing compilation time. It would probably also increase the size of your compiled binary.
Instead, there are other solutions in C++ could be used to get Θ(N) concatenation:
In this version, the string is modified in place, and while data that has already been copied into
resultsometimes needs to be recopied, C++ strings are typically implemented as dynamic arrays that allocate new space exponentially, so that the insertion of each new character takes amortized constant time, leading to overall Θ(N) behavior for repeated concatenation.The following is a way of doing the same thing, almost on one line. It uses the same principle internally, but also supports converting non-string types to strings using << overloading.
Lastly, the C++ standard library doesn’t include this, but one could define the following function with some stringstream magic inside it. The implementation is left as an exercise for the reader.
You can then call
concatfor repeated concatenation on one line in O(N) time:Presumably, all of these are better solutions than messing up type inference by creating an expression template type.