summaryrefslogtreecommitdiff
path: root/Optimizing-assembly-code.md
diff options
context:
space:
mode:
Diffstat (limited to 'Optimizing-assembly-code.md')
-rw-r--r--Optimizing-assembly-code.md63
1 files changed, 62 insertions, 1 deletions
diff --git a/Optimizing-assembly-code.md b/Optimizing-assembly-code.md
index 4e84545..c55d8fd 100644
--- a/Optimizing-assembly-code.md
+++ b/Optimizing-assembly-code.md
@@ -1,6 +1,6 @@
Sometimes the simplest way to write something in assembly code isn't the best. All of your resources are limited: CPU speed, ROM size, RAM space, register use. You can rewrite code to use those resources more efficiently (sometimes by trading one for another).
-Most of these tricks come from either [Jeff's GB Assembly Code Tips v1.0](http://www.devrs.com/gb/files/asmtips.txt), or [WikiTI's Z80 Optimization page](http://wikiti.brandonw.net/index.php?title=Z80_Optimization). (Note that Z80 assembly is *not* the same as GBZ80; it has more registers and some different instructions.)
+Most of these tricks come from [Jeff's GB Assembly Code Tips v1.0](http://www.devrs.com/gb/files/asmtips.txt), [WikiTI's Z80 Optimization page](http://wikiti.brandonw.net/index.php?title=Z80_Optimization), and [z80 Heaven's optimization tutorial](http://z80-heaven.wikidot.com/optimization). (Note that Z80 assembly is *not* the same as GBZ80; it has more registers and some different instructions.)
WikiTI's advice fully applies here:
@@ -19,6 +19,7 @@ WikiTI's advice fully applies here:
- [Set `a` to 0](#set-a-to-0)
- [Invert the bits of `a`](#invert-the-bits-of-a)
- [Set `a` to some constant minus `a`](#set-a-to-some-constant-minus-a)
+ - [Set `a` to one constant or another depending on carry](set-a-to-one-constant-or-another-depending-on-carry)
- [Multiply `hl` by 2](#multiply-hl-by-2)
- [Add `a` to a 16-bit register](#add-a-to-a-16-bit-register)
- [Add `a` to an address](#add-a-to-an-address)
@@ -111,6 +112,66 @@ But do:
```
+### Set `a` to one constant or another depending on carry
+
+Don't do:
+
+```asm
+ ; 6 bytes, 6 or 7 cycles
+ ld a, CONST
+ jr c, .carry
+ ld a, 0
+.carry
+```
+
+And don't do:
+
+```asm
+ ; 6 bytes, 6 or 7 cycles
+ ld a, 0
+ jr nc, .no_carry
+ ld a, CONST
+.no_carry
+```
+
+But do:
+
+```asm
+ ; 3 bytes, 3 cycles
+ sbc a
+ and CONST
+```
+
+Likewise, don't do:
+
+```asm
+ ; 6 bytes, 6 or 7 cycles
+ ld a, 0
+ jr c, .carry
+ ld a, CONST
+.carry
+```
+
+And don't do:
+
+```asm
+ ; 6 bytes, 6 or 7 cycles
+ ld a, CONST
+ jr nc, .no_carry
+ ld a, 0
+.no_carry
+```
+
+But do:
+
+```asm
+ ; 4 bytes, 4 cycles
+ ccf
+ sbc a
+ xor CONST
+```
+
+
### Multiply `hl` by 2
Don't do: