• Please review our updated Terms and Rules here

Z-80 tips for this day

gp2000

Experienced Member
Joined
Jun 8, 2010
Messages
466
Location
Vancouver, BC, Canada
A classic trick on the Z-80 to save a little bit of time and space is to use one of these instead of "LD A,0"

Code:
    XOR  A
    SUB  A

A very good replacement as long as alteration of the flags is not a problem.

However, in the name of robustness, a more modern "Trust, but verify" technique is preferred.

Code:
TOZ: DEC  A
     JR   NZ,TOZ

While heeding Knuth's words ("... premature optimization is the root of all evil (or at least most of it) in programming") it seems fair to optimize that approach a bit.

Code:
TOZ: ADD  A,A
     JR   NZ,TOZ

On the other hand a Monte Carlo approach may be called for.

Code:
TOZ: LD   A,R
     JR   NZ,TOZ

Ah, but those familiar with the Z-80 will have spotted a bug. The top bit of R register only changes when loaded. Easily fixed by elegantly mixing in the deterministic approach:

Code:
TOZ: LD   A,R
     ADD  A,A
     JR   NZ,TOZ

Should flag register changes be a concern we can borrow a technique from the MIPS processor which forces one of its registers to always be a zero value. After brief consideration, C is the obvious choice.

  • HL is too important addressing memory and doing 16 bit stuff.
  • DE is HL's understudy, ready to take over at a moment's notice (and an EX DE,HL).
  • DJNZ rules out B.
  • C pretty much looks like a 0 already.

While C may be needed for the odd LDIR this is no problem as it will be 0 after it executes. Now a quick

Code:
     LD   A,C

will do the TRICK. And it generalizes to all the other 8 bit registers. I hope these ideas will help improve your Z-80 programs. Have a nice DAY.
 
These ‘tricks’ save time and space at execution time, but not at software writing time...

They should be accompanied by suitable comments explaining the functionality of the optimisation. The more ‘obscure’ the optimisation is, the more comments there should be - especially if this is an esoteric use of an instruction or sequence of instructions.

Usually, optimisation to wring the maximum performance out of a machine is generally performed by highly qualified programmers that need to document their code for future (and potentially less experienced) software maintainers coming along after them.

The phrase “write once read never code” comes to mind!

Dave
 
At the moment all of the days, months and years all blend into one :).

That's my excuse, and I am sticking to it! My comment is still valid though for anyone reading it in 10 years time...

Dave
 
Back
Top