Manage memory in While loop

altric
altric used Ask the Experts™
on
Good day, everyone.

I have a function to carry out that is trying to insert 100,000 record into a table.

So, I try to implement in the following way:
--------------------------------------------------------
procedure form1.Button1Click(Sender: TObject);
var runLength, runtime : longint;
begin
runLength := 100,000;
runtime := 1;

While runtime <= runLength do begin
 tableX.Append;
 tableXName.value := 'cust' + IntToStr(runtime);
 runtime := runtime + 1;
 tableX.post;
end;
 
tableX.close;
end;
---------------------------------------------------------

The results of the above action makes my program freeze up.  Is it that I have not free up any memory that the loop consumes or else?

Please give me some advice on how to avoid program freeze up while running a long loop.

Thank you.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2004

Commented:
well, your gui may not responseable within the loop,
add application.processmessages in your loop,
maybe after every 10th insert
Top Expert 2004
Commented:
sample

...
While runtime <= runLength do
begin
  tableX.Append;
  tableXName.value := 'cust' + IntToStr(runtime);
  runtime := runtime + 1;
  tableX.post;
  if (runtime mod 10) = 0 then
    application.processmessages;
end;
...

meikl ;-)
VGR

Commented:
yes

your loop is perfectly valid and should complete.

You are doing 100 K inserts, this may take some time and your program ***seems*** to freeze, IMHO

Just add some tracing (to OutPut, to a logfile, to a table, to a TLabel somewhere etc) and you should be able to monitor the progress.
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

Hi,

I completely agree with what has already been said. Just a small addition. Add a label to your form:

While runtime <= runLength do
begin
 tableX.Append;
 tableXName.value := 'cust' + IntToStr(runtime);
 runtime := runtime + 1;
 tableX.post;
 if (runtime mod 10) = 0 then begin
   Label1.Caption := IntToStr(runtime); // to see the counter on the screen
   application.processmessages;
 end;
end;

Regards, Geo
after the line Label1.Caption := IntToStr(runtime); you might also want to add Label1.Refresh so that the caption is displayed :)

Author

Commented:
Thanks for everyone response.

But one more thing, I couldn't see the record display on the grid while the record is inserted.

May I know how to overcome it?

Author

Commented:
Thanks a lot guys!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial