Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to make your code faster
#3
And if you DO know some assembler, you can VERY easily use it in the compiler.

The important thing here, if you want to optimize routines is that you break the code into smaller pieces. If you ever were to write something in pure assembler, trust me, having the program made of small routines is going to be the ONLY way you can make it work. Probably.

Here's a small routine (stolen from Boriel):
Code:
FUNCTION  get () as uByte
DIM lastK AS uByte AT 23560: REM LAST_K System VAR
   LET  lastK=0
   DO LOOP until lastK <> 0 : REM Wait FOR a keypress
   RETURN lastK
END FUNCTION

What this does is set a variable at the Spectrum's system variable called LAST_K (address 23560) and wait for it to change. This routine requires interrupts enabled of course!

If all your program is broken down into small chunks like this (and it should be), then someone who knows assembler - even a little bit! - can start to replace little routines like this with assembler equivalents.
Don't worry if you can't - the compiler does make for fast code; but it's designed to work with all cases, and will probably never produce code quite as small and fast as an experienced human.

Anyway, here's machine code that does exactly the same thing in exactly the same way (this version stolen from Dr. Beep):
Code:
FUNCTION FASTCALL get () as uByte
asm
         ld   hl,23560 ; sysvar last key pressed
         xor  a  
         ld   (hl),a ; reset last key pressed
readkey: or   (hl)       ; test on change (this happens during intrupt)
         jr   z,readkey ; if no change, then read again
end asm
END FUNCTION

First of all it points hl at the variable LAST_K, and sets A to be zero (that's what XOR A foes).
Then it copies A over to LAST_K - just like the first version had LET lastK=0
Then it uses the OR function to combine LAST_K and A (in this case, it's the same as adding them together, since A=0) and if A is still zero, it goes back to "readkey".
Otherwise, A has a copy of LAST_K in it - and that's what the function returns. (Fastcall AS byte functions return what's in the A register).

Okay, this routine didn't save much because it wasn't speed critical [No routine that spends its time waiting can be called speed critical!] - but it does save several bytes over the compiled variation.

The key thing to note here is that this routine is a plug-in replacement for the first thing. It does the same thing in the same way. So, that's one routine replaced with assembler - if you replaced them ALL you'd have a 100% hand coded machine code program! Smile

Perhaps if you learn a little assembler, you can start mixing in assembly language with compiled code - and the ZX Basic compiler makes this really easy to do!
Reply


Messages In This Thread

Forum Jump:


Users browsing this thread: 2 Guest(s)