ReinetteII+.py, an Apple II plus emulator in Python
github.com
github.com
As a kid I remember spreading out the Apple II motherboard circuit diagram (part of the machine reference manual) on the floor and studying it. Good times.
Python doesn't have a case statement (which would be the natural way to do something like this in most languages) but I would have expected a dict function lookup would have been faster than the binary tree of if/else decisions.
In my implementation I usually store a dictionary entry with two function pointers. One for the opcode itself, and one for the addressing mode. Call the address mode to configure state correctly, then call the opcode to actually perform the work.
This is a lot cleaner than nested ifs.
This would just be an O(n) worst-case operation, the same as a non-optimized switch statement. In C/C++, Rust, etc it makes sense to use an array of function pointers as it degrades into a jump table, but not in Python. Same goes for an exhaustive and non-fallthrough switch statement.
Using a binary search tree (what this essentially is a flattened version of) halves the worst case.
For 8-bit CPUs, the more common paradigm is to use a giant switch statement and just order the OPs by frequency. You get the same Worst-Case, but a much better Average-Case.
Also, at least llvm is also clever enough to build a mix of binary search and jump tables for "sparse" switch case statements.
> In C/C++, Rust, etc it makes sense to use an array of function pointers as it degrades into a jump table [...]. Same goes for an exhaustive and non-fallthrough switch statement.
I have no doubt that non-exhaustive (sparse) switch statements can also be optimized in compilers today; the more important portion is the non-fallthrough aspect.
For most languages, a dense case statement is implemented via a jump table, a fast, constant time operation.
> In C/C++, Rust, etc it makes sense to use an array of function pointers as it degrades into a jump table [...]. Same goes for an exhaustive and non-fallthrough switch statement.
Having said that, I too wonder why they didn't use a dictionary. ;-)