Re: Faster way of making long string?



Thanks for this code.
It is blindingly fast and exactly what I was after!

I tested of 3 different methods of making the number string.
Each test went from i := 0 to 16383, and used a simple "IntToStr(i)" instead
of using TIntegerList to eliminate any overhead of the TIntegerList.

On my 1.3GHz Celeron results were:
1) MoveMemory method: 23 mS
2) TStringList.CommaText: 76 mS
3) The simple "join string" method (per original post): 186 mS

Thanks again,
Ian.

"Chris Willig" <chris_nospam_@xxxxxxxxxxxxxxx> wrote in message
news:PjLae.2$6z3.1@xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
> 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