Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an interpreter slower than a compiler in practice?

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!

like image 923
algorithmicCoder Avatar asked Nov 03 '11 08:11

algorithmicCoder


People also ask

Why is a compiler faster than an interpreter?

A compiled program is faster to run than an interpreted program, but it takes more time to compile and run a program than to just interpret it. A compiler indeed produces faster programs. It happens fundamentally because it must analyze each statement just once, while an interpreter must analyze it each time.

Why do compiled programs run faster than interpreted programs?

Programs compiled into machine code have a speed advantage over interpreted languages, as there is no intermediary step required before instructions execute on the processor.


1 Answers

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).

like image 169
Gustav Bertram Avatar answered Oct 18 '22 15:10

Gustav Bertram