6502 Interrupt Entry & Exit Techniques
Efficient interrupt handling on the 6502 processor often differs significantly from textbook examples found in introductory programming guides. Standard approaches frequently preserve registers unnecessarily, wasting valuable cycles that accumulate across the thousands of interrupts triggered each second during gameplay.
Conventional Approach (Less Efficient)
Typical entry sequences save all three registers regardless of whether the handler modifies them:
PHA(store accumulator on stack) – 3 cyclesTXA/PHA(move X to A then stack) – 5 cyclesTYA/PHA(move Y to A then stack) – 5 cycles
Restoration uses PLA/TAY/PLA/TAX/PLA/RTI, consuming 13 cycles on entry and 16 on exit. This defensive approach wastes cycles for handlers that only touch one or two registers.
Streamlined Method
Preserving only the registers actually modified within the handler improves efficiency dramatically. When only the accumulator gets used, which is common for simple raster color changes:
- Entry: Single PHA instruction (3 cycles, 1 byte)
- Exit: Single PLA before RTI (4 cycles, 1 byte)
These savings recover roughly one-third of a raster line worth of processing time compared to the full preservation approach. For handlers that fire multiple times per frame, the cumulative impact becomes substantial.
Additional Optimization Methods
- Zero-page preservation: Store to a zero-page location (
STA zpTemp) instead of pushing to stack. Restoration viaLDA zpTempsaves 1 cycle over PLA restoration while using equivalent memory - Self-modifying techniques: Write accumulator value directly into instruction operands for later retrieval. The saved value becomes part of a subsequent
LDA #nninstruction, eliminating the separate storage location entirely - Register choice optimization: Design handlers to use only the accumulator when possible, avoiding X and Y register involvement that would require additional preservation
Minimizing register usage matters beyond just preservation overhead. Loading 16-bit addresses into both X and Y registers when alternatives exist wastes both cycles and memory. Careful handler design considers which registers are truly necessary for the operation at hand.
See also: NMI setup tutorial · interrupt enable/disable debate · EOR assembly patterns