z80:Optimization

From Learn @ Cemetech
Jump to navigationJump to search

After you've worked the bugs out, you may if you wish make your program smaller and run faster. This section is dedicated to just that purpose. Although there are a lot of things you can do, here are some general things that can help:

Code replacements

xor a vs. ld a,0

A simple way to set a to zero. Don't use this if you want to preserve the flags.

or a vs. cp 0

It's smaller, and give you the same results.

Cursor/pen

   ld hl,$0100		;$01 is the row, and $00 is the column
    ld (curRow),hl
    ld (penCol),hl


This is much more efficient if you're going to change both cursor/pen positions. Because curCol is right after curRow (and penRow is right after penCol), you can use a 16-bit register to load both at once.

PutS

Something you may or may not know, it is that PutS and any other variation modifies HL to point to the byte after the null-term. This is very useful, especially when displaying multiple items to different locations on the screen without having to load string after string into hl.


   ld hl,txtTest
    bcall(_PutS)
    ld de,$0100
    ld (curRow),de
    ld hl,txtTest2
    bcall(_PutS)
    ;...
   
   txtTest:
    .db "Test",0
   txtTest2:
    .db "Test2",0

can be

   ld hl,txtTest
    bcall(_PutS)
    ld de,$0100
    ld (curRow),de
    ;we don't need "ld hl,txtTest2", because hl already points to txtTest2
    bcall(_PutS)
    ;...
   
   txtTest:
    .db "Test",0
   ;txtTest2			;Optional, doesn't affect speed or size here
    .db "Test2",0


It also allows you to display strings through a loop say, for a high score board.


   high:
    ld b,8
    ld de,0
    ld (curRow),de
    ld hl,txtHigh
   highloop:
   
    push hl
    push de
    ld a,(hl)
    ld h,0
    ld l,a
    bcall(_DispHL)
    pop de
    pop hl
   
    inc hl
   
    bcall(_PutS)
   
    inc e
    ld d,0
    ld (curRow),de
    djnz highloop
   
    bcall(_GetKey)
    ret
   
   txtHigh:
    .db 20,"HIGH SCORE!",0
   txt2nd:
    .db 19,"HIGH SCORE!",0
   txt3rd:
    .db 18,"HIGH SCORE!",0
   txt4th:
    .db 17,"HIGH SCORE!",0
   txt5th:
    .db 16,"HIGH SCORE!",0
   txt6th:
    .db 15,"HIGH SCORE!",0
   txt7th:
    .db 14,"HIGH SCORE!",0
   txt8th:
    .db 13,"HIGH SCORE!",0


Conclusion

From this point on, you may be perfectly happy with your program. It works, runs at a decent speed and is also smaller than it use to be. What more could there be to do? Read on to find out what else you need to do before you decide to release your program to the general public.