Table of Contents

Dispatching on a Byte

by White Flame and Krill

The need to dispatch to one of many possible routines based on the value of a byte comes up regularly if you're doing complex data-oriented routines like decompression or scripting, and most often needs to be as fast as possible.

All but the Stack Dispatch routine use self-modification, which will run 1 cycle faster and 1 byte leaner if the dispatch routine itself is in zeropage.

General Table Dispatch

128 entries or less

  sta :+ +1
: jmp (table)
 
table:
  .word handler0, handler2, handler4, ...

More than 128 entries

  asl
  bcs :++
  ; Dispatch 0-127
  sta :+ +1
: jmp (table)
  ; Dispatch 128-255
: sta :+ +1
: jmp (table + $0100)
 
table: .word handler0, handler1, ..., handler127, handler128, ...

Stack Dispatch

  tax
  txs
  rts

Low-Address Dispatch

  sta :+ +1
: jmp routine  ; Low byte is overwritten, high byte remains

High-Address Dispatch

  sta :+ +2
: jmp $0000  ; High byte is overwritten, low byte remains

Relative Branch Dispatch

  sta :+ +1
: bne *  ; If Z corresponds to A, otherwise use appropriate BRA