LB Booster
Programming >> Liberty BASIC language >> translation of FOR by LBB
http://lbb.conforums.com/index.cgi?board=lblang&action=display&num=1512939241

translation of FOR by LBB
Post by tsh73 on Dec 10th, 2017, 7:54pm

Hello Richard
by testing this code on JB forum
Code:
Print "Running 4 timed tests please wait..."
n = 100000
t = time$("ms")
x = 0 : i = 0
while i < n
    i = i + 1
    x = x + i
wend
t2 = time$("ms")
x = 0 : i = 0
[do]
    i = i + 1
    x = x + i
    if i < n then goto [do]
t3 = time$("ms")

x = 0 : i = 0
10
    i = i + 1
    x = x + i
    if i < n then goto 10
t4 = time$("ms")

x = 0
for i = 0 to n
    x = x + i
next
t5 = time$("ms")

print n; " times adding in While... Wend time is ";t2-t
print n; "     times adding in GOTO [do] loop time is ";t3-t2
print n; "     times adding in GOTO 10 loop time is ";t4-t3
print n; "     times adding in FOR loop time is ";t5-t4
 

I naturally run it in LBB as well, to see how it goes.
And in LBB FOR is significantly faster.
I turned on LBB pane - and I saw FOR translated to
Code:
25 FOR i = 0 TO n : WHILE 0 > n EXIT FOR : ENDWHILE
26 x = x + i
27 NEXT 

So I just wonder what
Code:
WHILE 0 > n EXIT FOR : ENDWHILE 

bit is for?

EDIT I wonder if it will run even faster without this check - it looks it is executed on every iteration.
Re: translation of FOR by LBB
Post by Richard Russell on Dec 10th, 2017, 9:20pm

on Dec 10th, 2017, 7:54pm, tsh73 wrote:
So I just wonder what WHILE 0 > n EXIT FOR : ENDWHILE bit is for?

It's to ensure that LBB accurately emulates LB's behavior when the 'initial conditions' of the FOR loop result in it not being executed at all. BBC BASIC always executes the body of the loop at least once irrespective of the initial conditions.

The somewhat strange formulation (using WHILE instead of IF) is necessary so that it works even if the loop is in a single-line IF clause such as this:

Code:
IF condition THEN FOR index = start TO end : PRINT index : NEXT : ELSE .... 

This is unlikely but LBB tries to cover even such eventualities, when possible!

Quote:
I wonder if it will run even faster without this check - it looks it is executed on every iteration.

You can easily do the test. If you specify the initial conditions as constants rather than variables LBB doesn't need to insert that code, because it knows that the special case doesn't apply. So you can compare the speed of these two versions:

Code:
n = 100000
t4 = time$("ms")
x = 0
for i = 0 to n
    x = x + i
next
t5 = time$("ms")
x = 0
for i = 0 to 100000
    x = x + i
next
t6 = time$("ms")

print n; " times adding in FOR loop (variable) time is ";t5-t4
print n; " times adding in FOR loop (constant) time is ";t6-t5 

Richard.

Re: translation of FOR by LBB
Post by tsh73 on Dec 11th, 2017, 05:06am

Thank you, Richard.