Re: Faster way of making long string?



Ian Hinson wrote:
I want to make a string of numbers from an integer list.
The code I'm using is pretty simple solution.

var
  i: integer;
  lstNumbers: TIntegerList;
  strOut: string;
begin
  strOut := '';
  if lstNumbers.Count > 0 then
  begin
    strOut := IntToStr(lstNumbers[0]);
    for i := 1 to lstNumbers.Count - 1 do
      strOut := strOut + ', ' + IntToStr(lstNumbers[i]);
  end;
end;

But I'm wondering whether this is an inefficient use of strOut.
It seems to me the program has to keep creating new instances of strOut,
then copy contents of previous instance into it (plus the new number of course).


Would using "SetLength" to increase the size of the string as required make a more efficient solution?
If so, could someone please give me an example how this could be done?


Thanks,
Ian.



procedure TForm1.Button1Click(Sender: TObject); const buf_sz = 200; var i, n, len, j : integer; strOut, s : string; begin if lstNumbers.Count > 0 then begin j := buf_sz; SetLength(strOut, j); n := 0;

    for i := 0 to lstNumbers.Count -1 do begin
      if i < lstNumbers.Count -1 then
        s := IntToStr(lstNumbers.Items[i]) +', '
      else
        s := IntToStr(lstNumbers.Items[i]);

      len := Length(s);
      if n +len > j then begin
        Inc(j, len +buf_sz);
        SetLength(strOut, j);
      end;

      MoveMemory(@strOut[n +1], @s[1], len);
      Inc(n, len);
    end;

    SetLength(strOut, n);
  end else
    strOut := '';

  Memo1.Text := strOut;
end;
.


Quantcast