Clojure 中“公共静态最终”的等价物是什么? Java 中的常量
我正在编写一些依赖于许多常量的 Clojure 代码。
它们将在紧密的内部循环中使用,因此 Clojure 编译器+JVM 组合尽可能高效地使用和优化它们非常重要。为了同样的目的,我通常会在 Java 中使用“public static final”常量。
声明这些的最佳方式是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我认为
def
-ing 全局命名空间中的东西已经是最接近的了。I think
def
-ing things in the global namespace is about as close as you can come.我相信 Clojure 1.3(或者可能是 1.4)允许您在
def
上放置一个^:constant
标签,向编译器表明这应该是一个常量,并且所有引用都应该在编译时解决。编辑
显然它是 Clojure 1.3,并且它是
^:const
,而不是^:constant
。有关摘要,请参阅 Clojure ^:const 工作原理?。I believe Clojure 1.3 (or maybe 1.4) allows you to put a
^:constant
tag on adef
, 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.没有 defconst,所以只使用全局 def 是惯用的;就优化而言,JIT 会让事情变得更快。
There's no
defconst
, so just using a global def is idiomatic; as far as optimisation is concerned, the JIT will make things fast.如果真的、真的、真的想要常量就位(我相信,JIT 会注意到该值是常量并做正确的事情),您可以使用宏。
这是相当丑陋的,但我想,性能关键的代码将永远是丑陋的。
不过,请注意您在宏中输入的内容!除了一些文字常量之外,我不会这样做。特别是不是对象。
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.
This is rather ugly, but performance critical code will always be ugly, I guess.
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。If just using
def
is not fast enough, you could try creating alet
bound alias before entering your tight loop to avoid going through a var each time.如上所述,使用 def 或atom,请记住,数据是不可变的,因此如果您在列表中声明一些常量,它们不会改变。
as said above use def or atom, remember, data is immutable, so if you declare some constants in a list, they don't change.