Efficient string concatenation?

Brad Anderson eco at gnuk.net
Fri Nov 15 14:33:33 PST 2013


On Friday, 15 November 2013 at 22:26:20 UTC, Jacek Furmankiewicz 
wrote:
> Since D strings are immutable (like in most other languages), 
> string concatenation is usually pretty inefficient due to the 
> need to create a new copy of the string every time.
>
> I presume string concatenation using the typical array syntax 
> can be optimized by the compiler to do all of this in one shot, 
> e..g
>
> string newString = string1 ~ string2 ~ string3;
>
> but what happens if I need to concatenante a large string in a 
> loop?
>
> I tried looking through Phobos for a StringBuilder class (since 
> that is the common solution in Java and C#), but did not find 
> anything similar.
>
> What is the D way of doing efficient string concatenation 
> (especially if it spans multiple statements, e.g. while in a 
> loop)?

Appender in std.array is probably what you are looking for.  
std.algorithm.joiner is also useful (no allocations at all even) 
but the use case is a bit different.


More information about the Digitalmars-d-learn mailing list