IF vs ON

STOS programming section.

Moderator: troed

Post Reply
User avatar
Site Admin
Site Admin
Posts: 7600
Joined: Wed Aug 16, 2017 11:19 pm
Location: UK

IF vs ON

Post by exxos » Tue May 22, 2018 1:51 pm

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..

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..


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 


Compiled outputs:

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.
4MB STFM 1.44 FD- VELOCE+ 020 STE - 4MB STE 32MHz - STFM 16MHz - STM - MEGA ST - Falcon 030 CT60 - Atari 2600 - Atari 7800 - Gigafile - SD Floppy Emulator - PeST - HxC - CosmosEx - Ultrasatan - various clutter

https://www.exxoshost.co.uk/atari/ All my hardware guides - mods - games - STOS
https://www.exxoshost.co.uk/atari/last/storenew/ - All my hardware mods for sale - Please help support by making a purchase.

Posts: 315
Joined: Mon Nov 13, 2017 7:19 pm
Location: Oxford, UK.

Re: IF vs ON

Post by stephen_usher » Tue May 22, 2018 6:56 pm

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.

Post Reply