Tips for fast string concatenation?

Steven Schveighoffer schveiguy at yahoo.com
Fri Jun 21 08:28:35 PDT 2013


On Fri, 21 Jun 2013 06:14:38 -0400, Jonathan M Davis <jmdavisProg at gmx.com>  
wrote:

> On Friday, June 21, 2013 12:09:09 Gary Willoughby wrote:
>> Have you any tips for using D when you need fast string
>> concatenation? I regularly use code like this:
>>
>>      foreach (i, range)
>>      {
>>          foo ~= bar;
>>      }
>>
>> or:
>>
>>      foo = foo ~ bar ~ baz ~ qux;
>>
>> I've used std.string.format(...) in some instances which sped
>> things up which surprised me.
>>
>> Are there faster ways of appending strings?
>
> In general, ~= will be faster, beacause it won't create temporaries like
> concatenating a bunch of strings in a single expression would.

I believe the above is one call to the runtime.

To answer the OP, using reserve will speed up the allocation quite a bit.   
Appender is certainly the fastest method.

-Steve


More information about the Digitalmars-d-learn mailing list