Repeat loop index

Richard Gaskin ambassador at fourthworld.com
Mon Jul 14 17:30:01 EDT 2003


erik hansen wrote:

> why should:
> 
> put (the number of lines in tText) into tTotal
> repeat with i = 1 to tTotal
>   doSomething(line i of tText)
> end repeat
>
> be any faster than:
> 
> put 0 into tCounter
> repeat for each line of tText
>   add 1 to tCounter
>   doSomething(line tCounter of tText)
> end repeat

Actually, that won't work: "repeat for each" requires you to specify a chunk
variable, like this:

 repeat for each line tMyLine of tText
   doSomething(tMyLine)
 end repeat

Why is it so much faster?

When you say:

   get line i of tText

...it has to walk through all the characters from the beginning, counting
carriage returns as it goes, until it reaches i number of lines.   This
creates a scaling problem:  the first time through the loop it's pretty
fast, but by the end it could be traversing hundreds or thousands of lines
each time through.  It does this with the most flexible assumption: if
something in the loop changes tText, only this brute-force method will
accurately count lines.

The "repeat for each" form works on a different assumption:  in cases where
you know tText won't change during the loop, the engine can afford to keep a
pointer into tText that tells it where it left off.  Each time through the
loop it only counts forward from where it last left off to the end of the
next line, so it scales beautifully:  each iteration takes almost exactly
the same time as the last.

And with specifying a chunk variable in the repeat statement, the chunk is
already parsed and stored in that var each iteration, ready for use.

-- 
 Richard Gaskin 
 Fourth World Media Corporation
 Developer of WebMerge 2.2: Publish any database on any site
 ___________________________________________________________
 Ambassador at FourthWorld.com       http://www.FourthWorld.com
 Tel: 323-225-3717                       AIM: FourthWorldInc




More information about the use-livecode mailing list