Search code examples
compiler-constructionvm-implementation

Interpreters vs Compilers vs Virtual Machines


I have a question about Interpreters, Compilers, and Virtual Machines (VMs).

Now I know the differences between Interpreters and Compilers but what is different about the VIRTUAL MACHINES from the previous 2? What are the Pros and Cons of a VM over Interpreters and Compilers?

Thanks a lot.


Solution

  • A virtual machine isn't exactly an alternative to compilers or interpreters. I think you are thinking of a JIT compiler, which is how many VMs are implemented.

    A virtual machine itself is exactly what the name says - it's a machine (processor) that doesn't actually exist. For example, most processors don't have any intrinsic way of dealing with memory allocation, or any knowledge of types. The Java VM though, has a new instruction that allocates an instance of a certain class. The designers of the VM decided that this was an important enough concept in the language to deserve its own opcode, which is the fundamental unit of operation in the VM.

    The advantages of creating your own instruction set are generally to bridge the gap between long compile/optimization times and slow interpreters. When you compile a Java class, for example, you don't have to do any register allocation or inlining or any of that traditional compiler stuff. The JIT will do that later, but only for the parts of code that you run enough times, and spread out over the run of the program. The JVM's instruction set is close enough to Java that the initial compile is quick, and it is simple and quick to read for the VM, unlike Java source code.

    As for interpreters vs JIT compilers, the tradeoffs are generally around runtime performance vs development time. A JIT takes a lot longer to develop, but an interpreter is a lot slower while running. In a lot of cases though, like scripting and small to medium sized websites, the program doesn't run long enough for you to really see any benefits of using a JIT.

    I should also mention software like VMware. This is also a virtual machine, but it uses an instruction set that also happens to be used on real hardware. It's the same basic concept as a language VM, in that it pretends to be a machine that isn't physically present, but in practice it's different and very complicated.