BBC BASIC for Windows
Programming >> BBC BASIC language >> ENDWHILE
http://bb4w.conforums.com/index.cgi?board=language&action=display&num=1242059049

ENDWHILE
Post by Michael Hutton on May 11th, 2009, 4:24pm

Why does ENDWHILE seem relatively slow?

from a profiler report:

Code:
     12134:       WHILE (this%<>0) AND (word$ > FNgetitem(index{}, this%))
     11088:       prev% = this%
     14153:       this% = index.link%
     77472:       ENDWHILE
 


surely it just loops back to the WHILE? or have I missed something?

Michael
Re: ENDWHILE
Post by JonR on May 11th, 2009, 8:04pm

Ask yourself not why the ENDWHILE line is slow but why the WHILE line is quick. On reaching ENDWHILE the interpreter evaluates the WHILE condition and only continues the WHILE loop if the condition evaluates to TRUE.
Re: ENDWHILE
Post by admin on May 11th, 2009, 10:39pm

Quote:
surely it just loops back to the WHILE?

It doesn't loop back to the WHILE - that would be inefficient. It loops back to the conditional expression in the WHILE statement (skipping the WHILE keyword entirely) and hence the evaluation of that conditional expression is counted by the profiler as part of the ENDWHILE statement.

Another way to look at it is to realise that if the initial condition is TRUE (i.e. the body of the loop is executed at least once) WHILE...ENDWHILE is executed by the interpreter exactly the same as REPEAT...UNTIL is: the conditional test is performed at the end of the loop, not at the beginning.

Effectively the code you listed is executed by the interpreter as if it was the following:

Code:
IF (this%<>0) AND (word$ > FNgetitem(index{}, this%)) THEN
  REPEAT
    prev% = this%
    this% = index.link%
  UNTIL NOT ((this%<>0) AND (word$ > FNgetitem(index{}, this%)))
ENDIF 

Richard.