As an exercise to help me learn about interpreters and optimisation, neither of which I know anything about, I have written a brainfuck interpreter in C. It appears to work flawlessly thus far, though it does not compete well in execution speed compared to other fast interpreters.
What are some ways that I can change this interpreter to improve performance (or otherwise)?
One interesting aspect of my interpreter (though most others probably do this as well) is that I run one loop that reads through the source input and converts each instruction into a
struct { long instruction; long loop; }
The loop
value is the index of the matching ]
instruction, if the instruction is a [
, and the index of the matching [
instruction, if the instruction is a ]
, allowing quick jumping. I'd imagine that this 'parsing' process (which doesn't take long) improves execution times over doing redundant reparsing to find matching square brackets every time they are needed.
An interesting test of brainfuck interpreter speed is this program:
++++++++[->-[->-[->-[-]<]<]<]>++++++++[<++++++++++>-]<[>+>+<<-]>-.>-----.>
- the first version of the interpreter
- the interpreter after implementing Jerry Coffin's answer, which removes the giant switch in the runtime loop, by making the
instruction
struct'sinstruction
a direct pointer to an operation function - this runs slower than the previous version (function call overhead?) - the interpreter after reversing the previous change and adding an optimisation to 'collapse' multiple consecutive non-loop operations, reducing loop cycles - this runs slightly faster than the original