The Ultimate Optimization

I got my first computer in 1984. It was a Commodore 64. I had to do extra chores and save up my allowance to buy it. I was 13.

Back then, Sears and other retail stores had Commodore 64 computers out on display. Whenever I went to the store, I’d write a short BASIC program and leave it running on the display computers:

10 PRINT "CRAIG IS GREAT!"
20 GOTO 10

Hey, I was a 13-year-old kid. Later, I got a little more sophisticated. I’d change the background color instead. I still remember the POKE address:

10 FOR I=0 TO 255
20 POKE 53281, I
30 NEXT I
40 GOTO 10
RUN

This was fast enough to change the background color every few scan lines, creating a flashing scrolling effect.

Later, I learned 6502 assembly language. I translated the BASIC program into assembler, and memorized the bytes to type in at the store. In assembly language, the background color would change several times per scan line. The effect was kind of psychedelic.

All that happened in the mid-1980s.

Fast-forward to about 2000 or so. I was telling the above story after a St. Louis LUG meeting. I explained how I had memorized the 10 or 12 bytes of machine code, and would leave the program running with its psychedelic effect.

After thinking about it for a bit, I thought that 10 or 12 bytes seemed too much. It actually bothered me — I couldn’t fall asleep when I got home. I got up and found my old 6502 manuals. I figured out how to write the code in 7 bytes. I installed the Vice C64 emulator on my Linux desktop, and tested my code. It worked as expected. (The emulator was already clock-cycle perfect by then.) Here’s the assembly code:

INX         ; $E8           ; 232
STX $D021   ; $8E $21 $D0   ; 142 33 208   ; $D021 = 53281
JMP $C000   ; $4C $00 $C0   ; 76 0 192     ; $C000 = 49152

Here’s the BASIC program to store that program in memory and run it:

10 FOR N=49152 TO 49152+6: READ Q : POKE N, Q : NEXT
20 DATA 232, 142, 33, 208, 76, 0, 192
30 SYS 49152
RUN

The moral of the story is that you can optimize even a 10-byte program, 15 years after the last time it was used. So don’t tell me that your program can’t be improved, no matter how small it is.

PS. I rewrote the code above while writing this article in 2015, about 15 years after the last time I rewrote it. And I again downloaded Vice to test it, this time on Mac OS X.

Leave a Reply

Your email address will not be published. Required fields are marked *