summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Optimizing-assembly-code.md67
1 files changed, 67 insertions, 0 deletions
diff --git a/Optimizing-assembly-code.md b/Optimizing-assembly-code.md
index 5ed248a..2ff7153 100644
--- a/Optimizing-assembly-code.md
+++ b/Optimizing-assembly-code.md
@@ -41,6 +41,7 @@ WikiTI's advice fully applies here:
- [Increment or decrement a 16-bit register](#increment-or-decrement-a-16-bit-register)
- [Add or subtract the carry flag from a 16-bit register](#add-or-subtract-the-carry-flag-from-a-16-bit-register)
- [Load from an address to `hl`](#load-from-an-address-to-hl)
+ - [Load from an address to `sp`](#load-from-an-address-to-sp)
- [Exchange two 16-bit registers](#exchange-two-16-bit-registers)
- [Subtract two 16-bit registers](#subtract-two-16-bit-registers)
- [Load two constants into a register pair](#load-two-constants-into-a-register-pair)
@@ -1273,6 +1274,72 @@ Instead, do this:
```
+### Load from an address to `sp`
+
+Don't do this:
+
+```asm
+ ; 9 bytes, 12 cycles
+ ld a, [Address]
+ ld l, a
+ ld a, [Address+1]
+ ld h, a
+ ld sp, hl
+```
+
+And don't do this:
+
+```asm
+ ; 7 bytes, 10 cycles
+ ldh a, [hAddress]
+ ld l, a
+ ldh a, [hAddress+1]
+ ld h, a
+ ld sp, hl
+```
+
+And don't do this:
+
+```asm
+ ; 7 bytes, 10 cycles
+ ld hl, Address
+ ld a, [hli]
+ ld h, [hl]
+ ld l, a
+ ld sp, hl
+```
+
+(That would be applying the "[Load from an address to `hl`](#load-from-an-address-to-hl)" optimization to the first way.)
+
+Instead, do this:
+
+```asm
+ ; 5 bytes, 8 cycles
+ ld sp, Address
+ pop hl
+ ld sp, hl
+```
+
+Or if the address is already in `hl`, then don't do this:
+
+```asm
+ ; 4 bytes, 7 cycles
+ ld a, [hli]
+ ld h, [hl]
+ ld l, a
+ ld sp, hl
+```
+
+Instead, do this:
+
+```asm
+ ; 3 bytes, 7 cycles
+ ld sp, hl
+ pop hl
+ ld sp, hl
+```
+
+
### Exchange two 16-bit registers
(The example uses `hl` and `de`, but any pair of `bc`, `de`, or `hl` would also work.)