10 ms·
Use enums for your op codes, and a switch statement (depends on compiler). If you use enums and a switch, the compiler can generate a jump table because it know
by Chirono 15y ago
Use enums for your op codes, and a switch statement (depends on compiler). If you use enums and a switch, the compiler can generate a jump table because it knows the enum will always be in a certain range. Much better performance than a bunch of if/else statements.
You can generate some beautifully simple interpreters this way, but switch/dispatch is not the way to go for high performance. Jump tables like that are not a good candidate for optimisation by compilers and they kill any sort of branch prediction your CPU is doing.
Here's an post (and follow up discussion) by the author of the Lua, where he explains why the main loop is written in assembler and why it beats compilers:
http://news.ycombinator.com/item?id=2588696 http://news.ycombinator.com/item?id=2588696