Hacker News new | ask | show | jobs
by csmuk 4571 days ago
No dictionaries are O(1). Even if they were they are pitifully slow compared to a switch. Consider chaining and the fact that you have to compute hashes.

switch is O(1) and fast as the operation is usually 2-3 deterministic time instructions:

1. Look up jump address from lookup table made by compiler.

2. Jump to it.

More people need to have written assembly to actually get this into their heads.

1 comments

In the case that the value you're switching on is a byte, and all 256 values are present in the case (very common for an 8-bit CPU emulator), a switch is a single instruction. You can't get faster/simpler than that.
Not to nitpick, but doesn't it need to be two instructions? You first do a relative jump by the value you're switching on, which takes you to another jump that jumps you to the actual code for that case. I can't think of a way to do it in just one instruction.
Just do an indirect branch, using a table of target pointers. If you had the opcode in eax, the single instruction would be something like:

    jmp  [lookupTable + eax]
Ah, good point. Thanks!