Conventions, Style, and Usage for Clojure Constants?

前端 未结 8 1222
余生分开走
余生分开走 2021-02-02 06:48

What are the best practices for defining constants in Clojure in terms of style, conventions, efficiency, etc.

8条回答
  •  北海茫月
    2021-02-02 07:11

    On the computational efficiency front you should know there is no such thing as a global constant in Clojure. What you have above is a var, and every time you reference it, it does a lookup. Even if you don't put earmuffs on it, vars can always be rebound, so the value could always change, so they are always looked up in a table. For performance critical loops this is most decidedly non-optimal.

    There are some options like putting a let block around your critical loops and let the value of any "constant" vars so that they are not looked up. Or creating a no-arg macro so that the constant value is compiled into the code. Or you could create a Java class with a static member.

    See this post, and the following discussion about constants for more info:

    http://groups.google.com/group/clojure/msg/78abddaee41c1227

提交回复
热议问题