Optimizing PET Speed
Michael W Schaffer
Careful numbering of program lines in Commodore Upgrade and 4.0 BASIC can improve the execution speed of GOTOs and GOSUBs. This technique is not applicable to the VIC-20, but the VIC is quite fast without it.
You can improve the efficiency of certain GOTOs and GOSUBs in your programs. The technique, though simple, is apparent only if you look at a disassembly of the BASIC ROM (it's at hex B830 in 4.0 ROMs).
The major overhead in the execution of GOTOs and GOSUBs is the time taken by BASIC to find the line number you are going to (the target line number). To start the search, BASIC first compares the high-order byte of the target line number to the high-order byte of the current line number. If the target high byte is larger, then BASIC starts to search at the next line of the program. Otherwise, BASIC starts the search at the beginning of the program.
Notice that BASIC only compares the high byte of the line numbers: small jumps forward may still be searched for from the beginning of the program. By carefully numbering the lines of your program, you can avoid this waste of time. The rule for this is simple:
Minimum target line number = 256*(INT(current line#/256) + l)
In a test program of 100 lines followed by a forward GOSUB, the speed of 100 executions of the GOSUB was improved by a factor of three by numbering the GOSUB as shown above. The amount of time saved is directly dependent on the length of your program and the position of the GOTO or GOSUB in the program, but can be significant, especially in user-interactive routines.
Program 1: Non-optimized GOSUB And Sample Run100 REM NOTICE THAT THE HIGH BYTES ARE E QUAL 250 T0=TI:FOR 1=1 TO 100:GOSUB 255:NEXT: PR INT"NON-OPTIMIZED"?(TI-T0):END 255 RETURNProgram 2: Optimized GOSUB And Sample Run
100 REM NOTICE THAT THE HIGH BYTES ARE NO T EQUAL 250 T0=TI:FOR I=1 TO 100:GOSUB 256:NEXT:PR INT"OPTIMIZED"; (TI-T0) :END 256 RETURN OPTIMIZED 19