Is Clojure compiled or interpreted?

8.2k views Asked by At

I read somewhere Clojure is compiled. Is it really compiled, like Java or Scala, rather than interpreted, like Jython or JRuby?

3

There are 3 answers

0
mikera On BEST ANSWER

Clojure is always compiled.

The Clojure compiler produces Java byte code, which is typically then JIT-compiled to native code by the JVM.

The thing that can be confusing is the dynamic and interactive nature of Clojure that means you can invoke the compiler at run-time if you want to. This is all part of the Lisp "code is data" tradition.

For example, the following will invoke the Clojure compiler at run-time to compile and execute the form (+ 1 2):

(eval '(+ 1 2))
=> 3

The ability to invoke the compiler at run-time is very useful - for example it enables you to compile and run new code in the middle of a running Clojure application by using the REPL. But it's important not to confuse this "interactive" style of development with being "interpreted" - Clojure development is interactive, but still always compiled.

2
Arthur Ulfeldt On

Both-ish! (when it comes to generating bytecode)

Clojure is on-the-fly-compiled at code load time into JVM bytecode, which has the feeling and flow of an interpreted language, and ahead-of-time compiled into JVM bytecode, which has the flow of a compiled language. both of these are then JIT compiled into machine code by the Java Hotspot compiler which takes care of the dynamic optimization that Clojure depends on for speed. just to make things interesting "loaded/evaluated" code can compile on the fly at runtime, and AOT compiled code can load and evaluate source at runtime.

  • If you want "interpreted" then you can (load "/my/file.clj") from the repl.
  • If you want Ahead-Of-Time compiling, may I suggest using the leiningen clojure project management tool.

In this case when i mention compiling vs. interpreting I should be clear that I am talking about turning source code into JVM bytecode. All JVM languages are compiled by the JVM at runtime so that distinction is not really very interesting.

0
kittylyst On

Clojure is a compiled JVM language. That means that the first step it takes when confronted with a new program is to compile it to JVM bytecode.

Some of the JVM bytecode may later be compiled to machine code by HotSpot, if you're using OpenJDK or a derivative of it.

As a high-level language, Clojure has a form of dynamic typing, which is what the "completely dynamic" phrase is referring to.