Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Loop Optimisation 1

Status
Not open for further replies.

sanka69

Programmer
May 15, 2002
6
0
0
GB
Hi all,
In C/C++ the following theory is correct, but does it apply for delphi?


--------------
var
i : integer;
a : array[0..10] of char;
begin

for i:=0 to High(a) do
begin
// some code
end

for i:=High(a) downto 0 do
begin
// some code.
end;

end;

The second for loop would be quicker since "High(a)" is only called once, instead of 10 times.

Thanks,
Richard
 
And in both cases it's pretty much irrelevant. The Delphi compiler creates blazingly fast code. I wrote a recursive routine that starts with four nested loops, and got worse from there; doing database accesses all the way down. I figured, I'll get it working, then I'll optimise it; but it ran so fast I never needed to.

Make your code readable first and hyper-efficient second, because unless you're running in some incredibly processor-starved environment, it's just not worth trying to optimise for a few extra clock cycles -- the computer time you save is much less than the programmer time you invest saving it. That's not to say that you should write massively inefficient code; just that that last few percent of optimisation isn't worthwhile. -- Doug Burbidge mailto:doug@ultrazone.com
 
Okay, thank you for your responses.

Regards,
Richard
 
Since it is a for loop, High(a) will only be evaluated once. If it would be evaluated every loop, you could affect the number of loops by changing the dimensions or size of a.

Besides that. The Delphi compiler is incredibly smart.
So since comparing a number with 0 is slightly faster than comparing with another number there's a good chance that the compiler will actually change your
[tt]for i := 0 to High(a) do[/tt]
to
[tt]for i := High(a) downto 0 do [/tt]

If your code allows it (depending on how you use i in the loop) the compiler will even eliminate i and use the registers of your processor instead.

In a while loop however, the expression is evaluated every loop. This should not be a problem, but it might be slightly faster if build it like this:
[tt]MyMax := High(a);
Count := 0;
while Count <= MyMax do[/tt]
So by saving the value of High(a), you prevent it being evaluated over and over again. This is typically useful if you use a more time consuming expression which High() obviously isn't.

Golez
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top