Switch statement with 256 cases?

I want to port a CPU emulator to Swift and need to dispatch on 256 opcodes. Will a switch statement with 256 cases (0-255) generate efficient code with some kind of direct dispatch? Or will it degenerate into a linear series of 256 if/else clauses?

Is there a better way to dispatch to 256 different sections of code? An array of blocks?

Have you considered this?

// Stateless
typealias Code     = Int
typealias Function = () -> Void

let instructions : [Code : Function] = [...]
// Stateful
typealias Code     = Int
typealias Function = (CPU) -> (() -> Void)
let instructions : [Code : Function] = [...]

class CPU {
   var pc : Int = 0
   ...

   // Instructions
   func I1 () {
      ...
   }
   ...
}

Why not just use the Code int to index into an array and skip the hashing?

2 Likes

That's the most optimal way, but would be possible only if the op codes were sequential.

1 Like

Switch is fine as long as you’re using a release build; I don’t know if a range-based branch or jump table implementation is guaranteed even with optimizations off. But it’ll definitely work with optimizations on.

3 Likes