views:

205

answers:

5

I'm writing some Clojure code that depends upon a number of constants.

They will be used within tight inner loops, so it's important that they will be used and optimised as efficiently as possible by the Clojure compiler+JVM combination. I would normally used a "public static final" constant in Java for the same purpose.

What is the best way to declare these?

+6  A: 

I think def-ing things in the global namespace is about as close as you can come.

Carl Smotricz
+2  A: 

as said above use def or atom, remember, data is immutable, so if you declare some constants in a list, they don't change.

Jed Schneider
If he wanted something mutable he would ask for a constant and anyway you woulnd normaly make a list with atoms. You would make a atom list or a ref list.
nickik
+2  A: 

There's no defconst, so just using a global def is idiomatic; as far as optimisation is concerned, the JIT will make things fast.

sanityinc
+3  A: 

If really, really, really want the constant in place (I believe, the JIT will notice the value being constant and do the right thing, though), you can use a macro.

(defmacro my-constant [] 5)

This is rather ugly, but performance critical code will always be ugly, I guess.

(do-stuff (my-constant) in-place)

Pay care what you put into the macro, though! I wouldn't this for more than some literal constants. In particular not objects.

kotarak
+2  A: 

If just using def is not fast enough, you could try creating a let bound alias before entering your tight loop to avoid going through a var each time.

Brian
Thanks - so am I correct in saying that if you don't do this, then it will end up dereferencing the var every time the constant is accessed?
mikera