开发者

Providing settable global vars

I need to provide settable vars for my user开发者_如何转开发s, like warn-on-reflection provided by clojure AFAIK they are not defined on the clojure side thats why we can set them.

Problem is my vars (all configuration stuff) are used in a lot of tight loops thats why I don't want to make them refs cause they MAY get set when application starts up and thats it no change during runtime, they will be read maybe millions of times so making them refs seems like wasting resources.

So the question is can I define settable vars in my case?


If you want settable global state with low overhead that is visible to all threads and doesn't need any STM transactions to control mutation, I'd recommend just using atoms:

(def some-global-value (atom 1))

Reads and writes to atoms are extremely low overhead.


warn-on-reflection is just a var, albeit one defined in Clojure's Java code rather than in core.clj. However, aside from where it is defined, there is nothing special about warn-on-reflection; it behaves exactly like any other var.

If you do not want to use vars, you may need to approach your problem from a different perspective than "must use global variables". It is common in functional programming to pass all necessary values into a function rather than relying on global variables. Perhaps it is time for you to consider such an approach.


You can create local binding using let, this way the parameters can be dynamic and you'll still have fast access. The only thing is that if someone change a parameter while the loop is running, the loop won't pick that up (IMO this should be the desired behaviour anyway).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜