Efficient string concatenation?

Justin Whear justin at economicmodeling.com
Fri Nov 15 14:30:35 PST 2013


On Fri, 15 Nov 2013 23:26:19 +0100, 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)?

std.array has an Appender type that can be used to build up a string (or 
any other array type) efficiently. E.g.:

auto strBuilder = appender!string;
while (...)
{
	str.put("foo");
}

// Get the array out:
string str = strBuilder.data;


More information about the Digitalmars-d-learn mailing list