Posted by webmaster Guido on April 06, 2007
In Reply to Re: delphi stringlist capacity posted by Jim on
March 31, 2007
Can you please show the "optimized" Delphi source code? And how you measure the timing
difference?
As explained before, the trick is in setting the stringlist capacity large enough, so that the program doesn't have to re-adjust the capacity many thousands of times when many items are added. If you want to add one million items, then you would optimize the code as follows:
SL.Capacity := SL.Count + 1000000;
for i := 1 to 1000000 do
SL.Add(...);
How to measure the timing? Let's assume a test form with an button, an edit-box, a checkbox and a label. When the button is clicked, a number of items is added, equal to what was entered in the edit-box. When the checkBox is checked, we preset the stringlist capacity, otherwise we leave it up to Delphi-behind-the-curtains to adjust the capacity dynamically. Here's the corresponding source code:
var SL: TStringList; procedure TForm1.FormCreate(Sender: TObject); begin SL := TStringList.Create; end; procedure TForm1.Button1Click(Sender: TObject); var StartTime: DWORD; i, ItemsToAdd: integer; begin ItemsToAdd := StrToInt(Edit1.Text); if CheckBox1.Checked then SL.Capacity := SL.Count + ItemsToAdd; // GetTickCount gives the number of millisecs since Windows started StartTime := GetTickCount; for i := 1 to ItemsToAdd do SL.Add('Delphi programming is fun!'); Label1.Caption := IntToStr(GetTickCount - StartTime); end; procedure TForm1.FormDestroy(Sender: TObject); begin SL.Free; end;
Related articles
Follow Ups