简体   繁体   中英

What is the Clojure equivalent of a “public static final” constant in Java

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?

我认为def全局命名空间-ing的事情是最接近你能来。

I believe Clojure 1.3 (or maybe 1.4) allows you to put a ^:constant tag on a def , signifying to the compiler that this should be a constant and all references should be resolved at compile-time.

Edit

Apparently it's Clojure 1.3, and it's ^:const , not ^:constant . See How does Clojure ^:const work? for a summary.

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

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.

如果只使用def不够快,你可以尝试在进入紧密循环之前创建一个let绑定别名,以避免每次都通过var。

如上所述使用def或atom,记住,数据是不可变的,所以如果你在列表中声明一些常量,它们就不会改变。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM