What are motivations behind compiling to byte-code?

sinan picture sinan · Jul 11, 2012 · Viewed 10.2k times · Source

I'm working on my own toy programming language. For now I'm interpreting the source language from AST and I'm wondering what advantages compiling to a byte-code and then interpreting it could provide me.

For now I have three things in mind:

  • Traversing the syntax tree hundreds of time may be slower than running instructions in an array, especially if the array support O(1) random access(ie. jumping 10 instructions up and down).
  • In typed execution environment, I have some run-time costs because my AST is typed, and I'm constantly traversing it(ie. I have 10 types of nodes and I need to check what type I'm on now to execute). Maybe compiling to an untyped byte-code could help to improve this, since after type-checking and compiling, I would have an untyped values and code.
  • Compiling to byte-code may provide better portability.

Are my points correct? What are some other motivations behind compiling to bytecode?

Answer

Fred Foo picture Fred Foo · Jul 11, 2012

Speed is the main reason; interpreting ASTs is just too slow in practice.

Another reason to use bytecode is that it can be trivially serialized (stored on disk), so that you can distribute it. This is what Java does.