[fpc-pascal] string concatenation speed

Michael Van Canneyt michael at freepascal.org
Tue Jun 21 19:46:17 CEST 2005



On Tue, 21 Jun 2005, Marc Santhoff wrote:

> Hi,
> 
> in an application of mine occurs a lot of string separation and
> re-concatenation. Since it is using masses of ANSI strings this is some
> performance problem.
> 
> The strings get stored and loaded from  TStringList's and concatenated
> by simply using '+' and separated with the function copy().
> 
> What I'd like to know is: What's are fastest ways of handling ANSI
> strings?

It's hard to say in general; You would have to supply some example code.

if you're doing things like
  For I:=X to Y do
   S:=S+L[i];  // S string, L list.

then
  It might be better to do

  Len:=0;
  For I:=X to Y do
    Inc(Len,Length(L[i]));  // S string, L list.
  SetLength(S,Len);
  P:=1;
  For I:=X to Y do
    begin
    T:=L[i];
    Len:=Length(T);
    Move(T[1],S[P],Len);
    inc(P,Len)
    end;

This will avoid a lot of calls to uniquestring, get/setlength etc.

Also, keep in mind that getting the I-th string from a list is an expensive operation.

So it is better to do
   T:=L[i];
   S:=Copy(T,X,Length(T)-X);
than to do
   S:=Copy(L[i],X,Length(L[i])-X);

The first option will call GetString only once, the second will call it twice.

This is the kind of thing you should pay attention to.

Michael.




More information about the fpc-pascal mailing list