I just ran across something rather interesting. I was writing a simple snippet of code to draw 360 dots of differing colors on the screen in succession, so I wrote this do loop:
count = 0
do
dot rnd(640),rnd(480),rgb(rnd(255),rnd(255),rnd(255))
count = count + 1
if count = 360
wait mouse
exit
endif
loop
Then I realized I could greatly shorten this by running a for loop instead:
for x=0 to 360
dot rnd(640),rnd(480),rgb(rnd(255),rnd(255),rnd(255))
next x
wait mouse
exit
This code ran instantly while the
do loop took about 5 seconds. This intrigued me enough to write this code:
hide mouse
count = 0
wtimer1 = timer()
while count < 361
color = rgb(rnd(255),rnd(255),rnd(255))
dot rnd(640),rnd(480),color
count = count + 1
endwhile
wtimer2 = timer()
sleep 500
cls
ftimer1 = timer()
for x=0 to 360
color = rgb(rnd(255),rnd(255),rnd(255))
dot rnd(640),rnd(480),color
next x
ftimer2 = timer()
sleep 500
cls
dtimer1 = timer()
count = 0
do
color = rgb(rnd(255),rnd(255),rnd(255))
dot rnd(640),rnd(480),color
count = count + 1
if count = 360
dtimer2 = timer()
gosub _prnt
wait mouse
exit
endif
loop
_prnt:
cls
wtime = wtimer2 - wtimer1
ftime = ftimer2 - ftimer1
dtime = dtimer2 - dtimer1
print "While: "; wtime; "ms"
print "For: "; ftime; "ms"
print "Do: "; dtime; "ms"
return
This last snippet simply doest the same code using 3 different loops and times them all. The results (on my machine) show the while loop took 5640 milliseconds, the for loop took 0 milliseconds, and the do loop took 5610 milliseconds. Why does it appear that the
for loop completes 360 iterations 5.6 seconds faster than the
while loop and the
do loop? I have a feeling it has something to do with my assumptions when writing the last experiment. Can anyone explain the vast time difference with these loops?
/* You are not expected to understand this. */
Dual Athlon 2.0/1GB RAM/GeForce Ti4200-128/Win2000 Pro