r/Clojure • u/alandipert • 12d ago
Mutable Locals in Clojure, the Hard Way
https://tailrecursion.com/~alan/Lisp/MutableLocals.html3
u/pwab 12d ago
Excuse my ignorance; what can you do with this that could not be done before? Or how does this elevate my thinking?
2
u/regular_hammock 12d ago
As a user, speed and lower heap churn (so, also speed). You would typically profile your application to find the bottleneck and hand optimise it. You could already do that for collections (using transients, or native arrays if you want to go further on the safety Vs speed axis), now you can also do it with scalar values.
Before, you would have had to write that mutable inner loop in java (or compromise on speed), which isn't ideal because a. it makes the build more complicated and b. now you have split your logic across two files and two languages, so the cognitive load for maintaining the code goes up.
To be fair, there's a lot of projects that won't benefit from this (because they're IO bound, or not intended to work at large scale, or not on any critical path...) but it's quite nifty.
As a reader of the blog post, you get an insight into a compiler technique.
2
u/alandipert 12d ago
Great summary, thanks! One qualification: ordinary Clojure
loop/recurcan already keep primitive long/double locals unboxed, so Java isn't required for efficient scalar loops. Whatloopholeadds is the ability to express assignments and early exits directly, while compiling them into that same machinery without mutable reference cells.It still inherits limitations of ordinary Clojure loops that can motivate writing Java. For example,
intloop counters get widened to longs, which has historically interfered with JVM optimizations in array loops.So,
loopholedoesn't eliminate every reason to reach for Java. Its main benefit is expressing certain algorithms more directly while still letting Clojure compile efficient primitive loops.
1
u/ak-coram 12d ago
Have you tried volatile!?
1
u/alandipert 12d ago
volatile!is a good comparison too. It avoids the thread-local lookup machinery used bywith-local-vars, but still stores values in anObjectfield, so primitive numbers are boxed.loophole, by contrast, compiles assignments and jumps into ordinary JVM locals, so numeric locals can stay unboxed where possible.Thanks for pointing out another alternative. I'll add it to the post.
7
u/regular_hammock 12d ago
Are you aware of
with-local-vars?Disclaimer: I really only skimmed your article so far, but on a superficial level it looks like it might do what you want.