REMINDER - Stay logged in for at least 2 hours a week to get whitelisted.
Also it helps build a picture where our "good traffic" is coming from for detection scripts.
:o)

IF vs ON

STOS programming section.
User avatar
exxos
Site Admin
Site Admin
Posts: 28487
Joined: 16 Aug 2017 23:19
Location: UK

IF vs ON

Post by exxos »

I did some quick tests to benchmark IF vs ON ...

Code: Select all

10 A=1
20 timer=0 : for Z=0 to 10000
30 if A=1 then gosub 110
40 next Z
50 print timer
60 timer=0 : for Z=0 to 10000
70 on A gosub 110
80 next Z
90 print timer
100 end 
110 return 
The timer to benchmark how long things take.

When run it outputs..
219
247

Which is a little odd as the whole idea of using ON is that it's supposed to be faster than using IF statements.

However when compiled it outputs..

40
39

So it is fractionally faster when compiled, but in this test there does not really seem to be much difference.

Next up a more complex test...

Code: Select all

10 A=1
20 timer=0 : for Z=0 to 10000
30 if A=1 then gosub 150
40 if A=2 then gosub 150
50 if A=3 then gosub 150
60 if A=4 then gosub 150
70 if A=5 then gosub 150
80 next Z
90 print timer
100 timer=0 : for Z=0 to 10000
110 on A gosub 150,150,150,150,150
120 next Z
130 print timer
140 end 
150 return 


outputs:
713
262

Compiled outputs:
85
39

So this now makes a lot more sense :) so if you only needed one IF condition, then using IF is probably fine as there is no real speed increase than using ON. However as most programs use multiple conditions, then clearly using ON results in double speed.
User avatar
stephen_usher
Site sponsor
Site sponsor
Posts: 7415
Joined: 13 Nov 2017 19:19
Location: Oxford, UK.

Re: IF vs ON

Post by stephen_usher »

That's logical.

ON with a single label will just be equivalent to an IF statement in terms of overhead, i.e. read line, parse, do test, do/don't do operation.

Where it excels is where it has multiple labels as there's only one set of read line, parse and do test. It can then just use a table for label location. The sets of IF statements have to this one at a time.

I'm not sure why the compiled version isn't better, unless there's no optimisation pass and it's outputing a direct translation of the BASIC code.
Intro retro computers since before they were retro...
ZX81->Spectrum->Memotech MTX->Sinclair QL->520STM->BBC Micro->TT030->PCs & Sun Workstations.
Added code to the MiNT kernel (still there the last time I checked) + put together MiNTOS.
Collection now with added Macs, Amigas, Suns and Acorns.

Return to “STOS”

Who is online

Users browsing this forum: CCBot and 5 guests