Hey,
This isn't really a question, more of a thought. Most people that I've read their questions on how to do a virtual machine use a switch statement for the reason that it's simple and all of the functions of the language go in the same place. But then the issue of speed always pops up, once the language gets more than 10 instructions. Some people suggest virtual functions or a function table, which is a good idea. However, I would just like to put my two cents in saying why don't you just use what you've used to sort data to call the commands? I.E. Here is a normal virtual switch statement:
switch (Cmd)
{
case 0: //do stuff
break;
case 1: //more...
break;
...
case 255: //last instruction...
break;
}
Correct? Now as you can guess if you're calling that 255th instruction it'll take awhile for the compiler to test to make sure the command is not all of the other commands. So why not break it into a hard-coded binary tree, or probably better just group the commands?
I.E.:
//Binary tree
if (Cmd < 128)
{
if (Cmd < 64)
{
if (Cmd < 32)
{ //ect down to....
...
if (Cmd == 0)
{
//do cmd 0
}
else
{
//do cmd 1
}
//or you could do it by grouping (it would be easier to add new commands)
//first ten cmds
if (Cmd < 10)
{
//switch statement/or more ifs to test the separate commands, or another group
}
else if (Cmd < 20)
{
//repeat
}
See? Now from my observances that would be easier to read and much faster than just one long switch statement. The groups could even have subgroups, say you go in groups of commands 100, then inside the 100 you partition it into 10. With the binary tree the last command would take 7-8 tests rather than 255, and with the grouping it'd take (assuming you're blocking by 100's then 10's) 12 tests. The advantage to blocking would be that more used functions can easily be placed at the beginning of the block, and would require less tests.
Tell me what you think.
Walt
Edit: Fixed source tags.
[edited by - shadowman13131 on June 16, 2003 11:44:04 AM]