46

I'm trying to understand what ^:const does in clojure. This is what the dev docs say. http://dev.clojure.org/display/doc/1.3

(def constants {:pi 3.14 :e 2.71})

(def ^:const pi (:pi constants)) (def ^:const e (:e constants))

The overhead of looking up :e and :pi in the map happens at compile time, as (:pi constants) and (:e constants) are evaluated when their parent def forms are evaluated.

This is confusing since the metadata is for the var bound to symbol pi, and the var bound to symbol e, yet the sentence below says it helps speed up the map lookups, not the var lookups.

Can someone explain the what ^:const is doing and the rationale behind using it? How does this compare to using a giant let block or using a macro like (pi) and (e)?

3 Answers 3

83

That looks like a bad example to me, since the stuff about map-lookup just confuses the issue.

A more realistic example would be:

(def pi 3.14)
(defn circ [r] (* 2 pi r))

In this case, the body of circumference is compiled into code that dereferences pi at runtime (by calling Var.getRawRoot), each time circumference is called.

(def ^:const pi 3.14)
(defn circ2 [r] (* 2 pi r))

In this case, circ2 is compiled into exactly the same code as if it had been written like this:

(defn circ2 [r] (* 2 3.14 r))

That is, the call to Var.getRawRoot is skipped, which saves a little bit of time. Here is a quick measurement, where circ is the first version above, and circ2 is the second:

user> (time (dotimes [_ 1e5] (circ 1)))
"Elapsed time: 16.864154 msecs"
user> (time (dotimes [_ 1e5] (circ2 1)))
"Elapsed time: 6.854782 msecs"
5
  • Does this mean that the following (def ^:const key-to-num {:one 1 :two 2}) (def sum (+ (:one key-to-num) (:two key-to-num)) is compiled to (def sum (+ 1 2)) ? Commented Aug 29, 2013 at 9:26
  • 1
    no, ^:const only works on primitive values, not arbitrary objects
    – noisesmith
    Commented Dec 9, 2013 at 17:00
  • How does this change with AOT compilation and direct linking? Do the performance benefits of ^:const go away in this case? Commented Nov 7, 2018 at 8:54
  • @JurajMartinka No, direct linking is for function calls only. AOT doesn't change anything. AOT just means the const inlining is done ahead of time, as opposed to just in time. So in both cases, const behaves the same and still benefits performance (marginally).
    – Didier A.
    Commented Jun 16, 2019 at 16:51
  • 1
    @noisesmith That's not true, const works on objects and values equally. Whatever is assigned to the const gets inlined. In robin-heggelund-hansen 's example, it gets inlined to: (def sum (+ (:one {:one 1 :two 2}) (:two {:one 1 :two 2}))). So you still avoid the Var lookup.
    – Didier A.
    Commented Jun 16, 2019 at 17:10
13

Besides the efficiency aspect described above, there is a safety aspect that is also useful. Consider the following code:

(def two 2)
(defn times2 [x] (* two x))
(assert (= 4 (times2 2)))    ; Expected result

(def two 3)                  ; Ooops! The value of the "constant" changed
(assert (= 6 (times2 2)))    ; Used the new (incorrect) value

(def ^:const const-two 2)
(defn times2 [x] (* const-two x))
(assert (= 4 (times2 2)))    ; Still works

(def const-two 3)            ; No effect!
(assert (= 3 const-two ))    ; It did change...
(assert (= 4 (times2 2)))    ; ...but the function did not.

So, by using the ^:const metadata when defining vars, the vars are effectively "inlined" into every place they are used. Any subsequent changes to the var, therefore, do not affect any code where the "old" value has already been inlined.

The use of ^:const also serves a documentation function. When one reads (def ^:const pi 3.14159) is tells the reader that the var pi is not ever intended to change, that it is simply a convenient (& hopefully descriptive) name for the value 3.14159.


Having said all the above, note that I never use ^:const in my code, since it is deceptive and provides "false assurance" that a var will never change. The problem is that ^:const implies one cannot redefine a var, but as we saw with const-two it does not prevent the var from being changed. Instead, ^:const hides the fact that the var has a new value, since const-two has been copied/inlined (at compile-time) to each place of use before the var is changed (at run-time).

A much better solution would be to throw an Exception upon attempting to change a ^:const var.

3
  • 2
    The Clojure Style Guide says "Don't use a special notation for constants; everything is assumed a constant unless specified otherwise." Does that suggest that values are routinely inlined, at least when they are not re-defed? (Maybe ^:const means only "might inline even if there is a later def of this variable", but if there isn't a later def, even non-^:consted vars might get inlined? My very wild guess.) Or if ^:consted vars are different, why shouldn't I make that explicit by naming, e.g. +name+ as in Common Lisp.
    – Mars
    Commented Apr 23, 2014 at 4:03
  • Using ^:const has 2 effects. (1) is that the compiler will inline the value, and will not use the var so you are immune to changes or abuse of the var. (2) is simply documentation; the author is claiming that the value should never change. Commented May 27, 2015 at 19:39
  • 1
    @Mars I believe the style guide means that Vars should be assumed constant, since in Clojure, it is discouraged to change the root value of a Var after it was set. A Var which changes, would normally be a dynamic Var, and be surrounded by earmuffs. So name would be assumed constant (as in it will never change, not as in compiler optimization or guarantee), and *name* would be assumed to be non constant. While ^:const is just to indicate to the compiler that he should optimize the code by inlining the use of the var.
    – Didier A.
    Commented Jul 8, 2017 at 6:43
11

In the example docs they are trying to show that in most cases if you def a var to be the result of looking something up in a map without using const, then the lookup will happen when the class loads. so you pay the cost once each time you run the program (not at every lookup, just when the class loads). And pay the cost of looking up the value in the var each time it is read.

If you instead make it const then the compiler will preform the lookup at compile time and then emit a simple java final variable and you will pay the lookup cost only once total at the time you compile the program.

This is a contrived example because one map lookup at class load time and some var lookups at runtime are basically nothing, though it illustrates the point that some work happens at compile time, some at load time, and the rest well ... the rest of the time

2
  • 2
    I don't think this is accurate. The more important savings is not the map-lookup, but the var-lookup for pi and e, which would occur every time you reference either of them if lacking the ^:const, but doesn't occur at all when ^:const is included.
    – amalloy
    Commented Feb 6, 2012 at 20:42
  • Thanks for pointing that out, I'v edited to add the var lookup also. Commented Feb 6, 2012 at 22:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.