Be sure to also check out the
6502 primer's page 20, "
Tips For Programming the 65(c)02 (sometimes affecting hardware design optimization)."
And as usual, I can't pass up the opportunity to recommend the excellent programming manual, "
Programming the 65816 including the 6502, 65C02, and 65802" by David Eyes and Ron Liechty. This is a .pdf file of a rather large book that is well laid out and is much better than the description there lets on. Note: There were many problems with the earlier .pdf version that were not in the original paper manual; but in late March 2015, WDC scanned and OCR'ed the paper manual and posted the new, repaired .pdf.
In my
6502 assembly structure macros, the macros for a FOR...NEXT loop like your above watch for that kind of thing, to optimize. So
Code:
FOR_X 20, DOWN_TO, 0
<do stuff>
<do stuff>
NEXT_X
would assemble
Code:
LDX #20
loop: <do stuff>
<do stuff>
DEX
BNE LOOP
without the CPX #0; but CPX would be added if you had for example FOR_X 20, DOWN_TO,
4. (It is slightly modified from BASIC's FOR...NEXT to more closely match what we do in assembly. The destination number is not run, because the incrementing or decrementing happens right before the test and conditional branch.) There are many conditions you can set up, and the macros will watch for them and optimize, just as you would do by hand, except that now the source code becomes more readable, so you get fewer bugs, quicker development, and better maintainability.