I wrote an interpreter in JavaScript for a small language using jison, which is a JS port of bison. The language is used to evaluate expressions and conditions. Right now the evaluation is mixed with the parsing.
I’m trying to optimize it and the bottleneck is lexer and the parser. So I decided to parse it before hand and only evaluate on runtime.
The question is that which one is faster or cleaner, generate JS code before and only run that or generate AST and iterate on it on runtime?
In general*, faster will always be to generate anything that is closest to machine code. In your case generating javascript would be faster.
The generated javascript code would be executed directly by the underlying C/C++ interpreter (and in some cases compiled JIT into machine code). In contrast, writing your own VM in javascript to execute the AST would run on an additional layer of VM – javascript.
*note: There are some corner cases where interpreters can sometimes execute as fast as native code. Forth being an example because it’s interpreter is dead simple – it’s just a table of function pointers.