Sunday, June 10, 2007

Interpreters vs. Compilers

When I was first learning computer science, I used to wonder the distinction between a compiler and an interpreter. Honestly, it helps to write one or the other to know the difference.

I think it's easier to explain a compiler. A compiler takes a (mostly) human-readable program written in some language and (typically) translates this to machine code. CPUs , at its lowest levels, execute machine instructions. Typically, people compile code because running native machine code is faster than handling interpreted code.

Here's an analogy. Suppose you want to write an instruction manual. You have it written in English, but you intend for it to be used by Japanese folks. So you have the stuff translated to Japanese.

What's an interpreter? An interpreter is a program that understands a program you've written, and runs it on the fly. Let me give you an analogy, although this is a programming analogy.

Suppose you want to write a "robot language". You can tell the robot to move forward, turn left, turn right, etc. You can either convert this robot language directly to machine code, or you can write a program that incrementally processes it. When the user wants to robot to move forward, you call some code to move it forward.

Typically, interpreters are used in an "environment" where the user can make decisions on the fly, and the interpreter can offer commands to the interpreter as well as run code. The code it runs may not be converted directly to machine code and optimized, but is run though high level programming language code.

Wow, this is really hard to explain. Hmm, I think the closest analogy I can think of is that a compiler is like having a series of detailed explanations completely worked out and sent to someone. They can't ask you for more help afterwards. An interpreter is more like having a person answer your questions as needed. In other words, the interpreter is a program that serves as a kind of middleman, being able to handle commands as you type it in, while a compiler expects all of its input to exist right away, and makes a complete translation to lower-level code.

There's a software engineering analogy. A compiler is closer to the "big design up front" while an interpreter is more like agile design, where the customer can make changes along the way.

Fundamentally, they share stuff in common (basic parsing and such), but the goal of n interpreter is interactivity between the user and the interpreter where as a compiled program is meant to just run (it can have interactivity too, but not with the developer).

Ugh, I wonder what's a better way to explain the difference.

No comments: