Re: delphi stringlist capacity

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

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:

  SL: TStringList;

procedure TForm1.FormCreate(Sender: TObject);
  SL := TStringList.Create;

procedure TForm1.Button1Click(Sender: TObject);
  StartTime: DWORD;
  i, ItemsToAdd: integer;
  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);

procedure TForm1.FormDestroy(Sender: TObject);

Related articles


Follow Ups