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.
sta :+ +1 : jmp (table) table: .word handler0, handler2, handler4, ...
SBC
/ASL
to adjustasl bcs :++ ; Dispatch 0-127 sta :+ +1 : jmp (table) ; Dispatch 128-255 : sta :+ +1 : jmp (table + $0100) table: .word handler0, handler1, ..., handler127, handler128, ...
tax txs rts
TAX
is necessarysta :+ +1 : jmp routine ; Low byte is overwritten, high byte remains
sta :+ +2 : jmp $0000 ; High byte is overwritten, low byte remains
sta :+ +1 : bne * ; If Z corresponds to A, otherwise use appropriate BRA