Hacker News new | past | comments | ask | show | jobs | submit login

why not use an array of structs as the program, with a function pointer and the parameters stored in the struct? the instruction pointer is then an index into that array... the functions implement the opcodes and the archetecture becomes more instructive, cleaner, faster, smaller and easier to read imo. executing the program can become a loop that just calls whatever function pointer is in the struct at the instruction pointer.



Funny you mention that - I used that structure in my simple virtual machine (which includes a compiler, a decompiler, support for conditionals, and also an example of embedding):

https://github.com/skx/simple.vm

Rather than having an enum of opcodes I have a array of pointers to functions - one for each opcode I implement. It is a logical/clean way of implementing things, but i think it is not necessarily better.

(In my case I lose due to inline strings, and variable length opcodes which make complications.)


As already suggested, function pointers are a particularly memory inefficient way to represent instructions/opcodes.

But on top of that, there is another issue with this representation: Your interpreter will very likely be dog slow, because you have to make a function call on each iteration, and it cannot be inlined, because it is dynamic.

And I suspect there are implications for the I-Cache that should probably be considered as well.

EDIT By "considered", I mean, measured, and then considered.


Not very memory-efficient and not very much like a real instruction set.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: