Hamza Yerlikaya
Hamza Yerlikaya

Reputation: 49339

Providing settable global vars

I need to provide settable vars for my users, 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?

Upvotes: 4

Views: 330

Answers (3)

mikera
mikera

Reputation: 106391

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.

Upvotes: 2

user100464
user100464

Reputation: 18459

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.

Upvotes: 1

Miki Tebeka
Miki Tebeka

Reputation: 13910

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).

Upvotes: 1

Related Questions