Why is an interpreter slower than a compiler in practice?

algorithmicCoder picture algorithmicCoder · Nov 3, 2011 · Viewed 14.2k times · Source

Don't they both have to convert to machine code at some point to execute or am i missing something more basic?

EDIT:

Please consider more sophisticated interpreting schemes e.g. cases where the code is translated to Byte code and the byte code is only regenerated when source code changes e.g. CPython implementation of Python? I am not really interested in ancient interpreters that re-execute line by line....

Thanks!

Answer

Gustav Bertram picture Gustav Bertram · Nov 3, 2011

A compiled language like C is usually compiled directly into machine code. When you run the code, it is executed directly by the CPU.

A fully interpreted language like BASIC or PHP is usually interpreted each time it runs. When you execute your code, the CPU executes the interpreter, and the interpreter reads and executes your source code. (PHP can be classified as fully interpreted, since while it does use opcodes, they are usually thrown away after the execution.)

A bytecode interpreted language like Python, is compiled from source code to bytecode that is executed by a virtual machine. The CPU runs the VM, and the VM executes each bytecode instruction. In Python, the bytecode is compiled the first time code is executed.

In Java, bytecode is compiled ahead of execution. The Java VM also has a special feature called Just-in-time compilation. This means that during execution, it may compile some of the bytecode to machine code, which it can send to the CPU to execute directly.

In conclusion, with compiled languages, the CPU runs the code directly. In interpreted languages, the CPU usually runs the interpreter or virtual machine. This makes interpreted languages generally slower than compiled languages, due to the overhead of running the VM or interpreter.

NOTE: While we speak of interpreted and compiled languages, what we are really discussing is the usual execution style of a language. PHP can be compiled (using HipHop), and C can be interpreted (using Parrot VM).