Programming with Ophis | ||
---|---|---|
<<< Previous | Pointers and Indirection | Next >>> |
Pointers are slow. It sounds odd saying this, when C is the fastest language around on modern machines precisely because of its powerful and extensive use of pointers. However, modern architectures are designed to be optimized for C-style code (as an example, the x86 architecture allows statements like mov eax, [bs+bx+4*di] as a single instruction), while the 6502 is not. An (Indirect, Y) operation can take up to 6 cycles to complete just on its own, while the preparation of that command costs additional time and scribbles over a bunch of registers, meaning memory operations to save the values and yet more time spent. The simple code given at the beginning of this essay—loading *b into the accumulator—takes 7 cycles, not counting the 6 it takes to load b with the appropriate value to begin with. If b is known to contain a specific value, we can write a single Absolute mode instruction to load its value, which takes only 4 cycles and also preserves the value in the Y register. Clearly, Absolute mode should be used whenever possible.
One might be tempted to use self-modifying code to solve this problem. This actually doesn't pay off near enough for the hassle it generates; for self-modifying code, the address must be generated, then stored in the instruction, and then the data must be loaded. Cost: 16 cycles for 2 immediate loads, 2 absolute stores, and 1 absolute load. For the straight pointer dereference, we generate the address, store it in the pointer, clear the index, then dereference that. Cost: 17 cycles for 3 immediate loads, 2 zero page stores, and 1 indexed indirect load. Furthermore, unlike in the self-modifying case, loops where simple arithmetic is being continuously performed only require repeating the final load instruction, which allows for much greater time savings over an equivalent self-modifying loop.
(This point is also completely moot for NES programmers or anyone else whose programs are sitting in ROM, because programs stored on a ROM cannot modify themselves.)
<<< Previous | Home | Next >>> |
What about Indexed Indirect? | Up | Conclusion |