string manipulation performance

Lloyd Dupont ld-REMOVE at galador.net
Sun Jun 12 18:02:05 PDT 2011


But... string being immutable I don't see the point of allocating some space 
for one..
Am I missing something?

"Steven Schveighoffer"  wrote in message 
news:op.vwy503w4eav7ka at localhost.localdomain...

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

-Steve 



More information about the Digitalmars-d-learn mailing list