## Speeding up For/Next loop.

Feel free to post 'can't wait' JB programming questions in this area until the forums are up again.
John Davidson
Posts: 128
Joined: Sat Nov 13, 2004 8:36 am
Location: Vashon Wa

### Speeding up For/Next loop.

There is a another discussion about looping and it appears that it is faster to use random numbers to find a user input than a for/next loop.
This may be the case when looking for large numbers in large loops but loops can be pared down to smaller, and faster, chuncks.

Sort of like a pre-search to setup the starting and finishing numbers used by a for/next loop. .

For example, if the user has input 5023, it would serve no purpose to search numbers smaller than 5000.
The demo below loops a maximum of 1000 times so it would set the maximum loop to 5999.

Adding an Exit For makes this is so fast that it usually can't be timed.
The demo tries pretty hard to calculate the time it takes to find the number but I suspect it is only a guess when it's greater than zero...

It could be made even faster by cutting the Select Case in half.
This would be done first checking to see if the number input is greater than 4999.
Numbers greater would pre-search only numbers above 4999, smaller numbers would pre-search numbers below 5000.

John

Code: Select all

``````    input "Enter 4 digit number ";num\$
v= val(num\$)
if v=0 or v>9999 then
print "Out of range."
end
end if
print
n\$=left\$(num\$,1)

startTime=time\$("ms")

select case n\$
case "0"
start=9
fin  =999
case "1"
start=1000
fin  =1999
case "2"
start=2000
fin=  2999
case "3"
start=3000
fin=  3999
case "4"
start=4000
fin=  4999
case "5"
start=5000
fin=  5999
case "6"
start=6000
fin=  6999
case "7"
start=7000
fin=  7999
case "8"
start=8000
fin=  8999
case "9"
start=9000
fin=  9999
end select

for x=start to fin
if x=v then exit for
next

print "Checked numbers ";start;" - ";fin
t=time\$("ms")-startTime
print "Found ";num\$;" in ";t;" ms"
end``````
John Davidson
e-me: johnshomeport@yahoo.com
My JB Page: http://john.jbusers.com/
Did ya Libby yet? http://lblibby.com/

TheSurvivor903
Whoa! That was fast! I expected it to go slower and give me a number in a few seconds but it actually did it IMMIDEATLY as I pressed enter. (Guess this is the new conforums for now? Not too many people have noticed...)

Posts: 7
Joined: Tue Mar 25, 2008 7:17 pm
Very cool! I liked how you utilized select case