4 ms·
> Personally, I prefer having a switch since it's more obvious which opcode goes where. In practice, having a switch is not worse or can even be better for per
by bluetomcat 5y ago
> Personally, I prefer having a switch since it's more obvious which opcode goes where.
In practice, having a switch is not worse or can even be better for performance because any non-naive optimising compiler will emit a nicely ordered indexed jump table, whereas following function pointers involves more indirection through the addresses of the functions, and has the additional overhead of passing args and preparing/restoring the stack.
- nomemory 5y agoI've thought of that, and to be honest I think it's worth mentioning in the article. But having set this arbitrary limit to 125 lines, before even starting to sketch things down, made me use the function tables. As a plus, article is intended for beginners, and it would be cool if they learn about function pointers from a practical example. But from a performance perspective, you are right!
- WGH_ 5y agoThere's also "computed gotos". It's not the same as function pointers, though. https://eli.thegreenplace.net/2012/07/12/computed-goto-for-efficient-dispatch-tables https://eli.thegreenplace.net/2012/07/12/computed-goto-for-e... - article about them being used in CPython
- MaxBarraclough 5y agoGforth uses the same trick. https://www.complang.tuwien.ac.at/forth/threaded-code.html https://www.complang.tuwien.ac.at/forth/threaded-code.html
- MaxBarraclough 5y agoFurther to this: this kind of thing is something the Forth community takes seriously. They call these threaded code techniques. [0] (The Gforth interpreter, for instance, gives you the choice of various different techniques.) Anton Ertl of Gforth fame published a microbenchmark performance comparison of toy interpreters, written in C, run on various CPUs. [1] As you say, the approach using function pointers (call threading) scores poorly. Interestingly, direct threading and indirect threading are extremely close, with the winner seeming to depend on the specific CPU. [1] Branch-prediction differences seem to be the main reason. There was a 2001 paper on this. [2] [0] https://www.complang.tuwien.ac.at/forth/threaded-code.html https://www.complang.tuwien.ac.at/forth/threaded-code.html [1] https://www.complang.tuwien.ac.at/forth/threading/ https://www.complang.tuwien.ac.at/forth/threading/ [2] https://github.com/ForthPapersMirror/Papers/blob/master/ConvertedToPDF/The-behaviour-of-efficient-virtual-machine-interpreters-on-modern-architectures--ertl-gregg01.pdf https://github.com/ForthPapersMirror/Papers/blob/master/Conv...