string manipulation performance

Jonathan M Davis jmdavisProg at gmx.com
Sun Jun 12 13:13:19 PDT 2011


On 2011-06-12 11:08, Steven Schveighoffer wrote:
> On Sun, 12 Jun 2011 12:49:25 -0400, Lloyd Dupont <ld-REMOVE at galador.net>
> 
> wrote:
> > I have a method like that:
> > ===
> > public string repeat(string s, int num)
> > {
> > 
> >     string result = s;
> >     for (int  i=1; i<num; i++)
> >     
> >         result ~= s;
> >     
> >     return result;
> > 
> > }
> > ===
> > basically it will create num string, each a little longer...
> > is there a more efficient way to go about that?
> > thanks! :)
> 
> The runtime tries its best to avoid allocating a new string on each
> append.  Please read the manual on appending, and you also might want to
> check out an article I wrote about slices that deals with appending.  The
> runtime also provides functions to pre-allocate an array for appending.
> For example:
> 
> 
>   public string repeat(string s, int num)
>   {
>       string result = s;
>       result.reserve(s.length * num); // ensure result can append all the
> repeated data without reallocating
>       for (int  i=1; i<num; i++)
>           result ~= s;
>       return result;
>   }
> 
> 
> http://www.digitalmars.com/d/2.0/arrays.html#resize
> 
> http://www.digitalmars.com/d/2.0/phobos/object.html#reserve
> 
> http://www.dsource.org/projects/dcollections/wiki/ArrayArticle

Also, std.string.repeat has been scheduled for deprecation. You should use 
std.array.replicate instead. It does the same thing but for all arrays instead 
of just strings.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list