C++ – way to speed up a big switch statement

coptimizationsimulationswitch statement

As a practice I'm working on a CPU simulator (runs at about 1.78MHz) and I'm using a switch statement to execute correct opcodes based on the value in the IR (instruction register) variable. This switch statement needs 256 cases. While it may not be that big, the switch statement needs to be executed many times in a short period of time. Are there any better ways to make fast code than using a switch statement for the same purpose?

The opcodes can be broken into two parts: Addressing mode and the actual operation. For compact code these probably could be arranged into functions and placed in the cases based on which ones are needed. I'm just not sure if writing each one out separately would be much more efficient though even if it makes the code itself larger.

Another idea, which I'm not sure how to do yet, is that I could try to detect the addressing mode and operation from the opcode before the switch statement(s) and then use one to run the addressing modes to get the effective address and then a second switch statement to perform the actual operation (and write back to memory if it was RMW instruction).

So any thoughts? Is switch statement the best choice here and what other optimization can I do to make sure the simulation runs fluently?

Best Answer

For an architecture such as this, a switch statement is actually pretty efficient. If your target speed is 1.78 MHz (sounds like some Z80 machine, the TRS-80 model II had this clock speed) and your emulator runs on a modern CPU, you really shouldn't worry about this detail though, your emulator will be fast enough.

More speed can be achieved by doing just-in-time compilation of emulated machine code to native code, but it is very unlikely that you need this.